Javascript tip - You are working away on a page in PHP or ColdFusion or whatever and you want to capture some information like an environmental variable but you don't want to submit the page to get that information to your server how do you do it?
Probably lots of ways to do it, but this one is cool.
Cancatenate your information, the URL of the page plus all the info that you want to be processed with that URL into a string and put it into a variable. Then convert the string into a form that a form would use to submit info. You can do this a lot of ways, but I use the simple regular expressions here. With a small string, this is fine, but if you are processing a larger bloack of text, then you would want to do one complex regular expression rather than four. Then you create an new image using Javascript and then set the location for the image to the variable that you created from the info and viola, the processor is run without ever opening in the browser window.
/* cancatenate the string of the URL and the variables you are passing into a JS variable */ var mystring="processor.cfm?var1=" + var1 + "&var2=" + var2; /* use regular expressions to change the required characters in the string. You can probably do this better, but this works for short strings */ var mystring = mystring.replace(/s/g, "+"); var mystring = mystring.replace(///g, "%2F"); var mystring = mystring.replace(/(/g, "%28"); var mystring = mystring.replace(/)/g, "%29"); var mystring = mystring.replace(/;/g, "%3B"); /* test your string, it should now be encoded like a form would encode the string to go to the processor.*/ alert(mystring); /* create a new image from the image object and set that to the URL that you created in the string and encoded */ var myconnect = new Image(); myconnect.src = mystring;
Now you have taken info from the page and submitted it to a processor without ever changing the page and disrupting the user's browsing experience. Why would you do this instead of just using an app server? Because active pages are extended on the app server when you access them, they cannot access information that exists when the page is loaded in the browser like the width or the height of the broser. Using this technique you can combine info you get from JS and from your app server and then send that back as one unit to your app server.
(Thanks Christian. Our new Server Products Community Manager helped me out on this one.)
3:30:24 PM
|