|
Javascript passing variables to coldfusion |
I was looking to capture the screen resolution for an application, and there didn't seem to be a straightforward way of doing that in coldFusion. JavaScript can do it, so how do I join the two together.....
First, build a form, and embed it in a javascript function. This is an entirely hidden form, all the elements are hidden. Then we populate two hidden fields with the values passed from the call to the method below. This is the screen height, and screen width.
End the function with a submit method, IE it submits itself.
2 function screenResolution(width,height) {
3 document.write('<form name="hiddenForm" action="action.cfm" method="post">');
4 document.write('<input type="hidden" name="width" value="' + width + '">');
5 document.write('<input type="hidden" name="height" value="' + height + '">');
6 document.write('</form>');
7 document.hiddenForm.submit();
8 }
9</ script>
Add an event to action the method....
This will submit the hidden form to 'action.cfm' where you can do whatever you want with the form variables. For example:
2
3<cfset application.screenWidth = form.width>
So our javascript determined variables are passed into coldfusion. Would be nice if it was server side, rather than a submit function, but I'm working on that.
Amend:
I've since discovered that this doesn't work in FireFox. It doesn't submit the form at all, in fact it can't even find the form in the DOM.So another solution would be to use the same hidden form as normal html, with no values in the fields.
2 <input type="hidden" name="width" value="">
3 <input type="hidden" name="height" value="">
4</form>
Then in your function send the screen width and height into it, like this:
2 function GetScreen() {
3 document.forms.hiddenForm.width.value = screen.width;
4 document.forms.hiddenForm.height.value = screen.height;
5 document.forms.hiddenForm.submit();
6 }
7</script>
8
9<body onload="GetScreen();">
Then its cross browser compatible!