9.2 Embedding Javascript | |
Another common task Vortex programmers encounter is sending Javascript to a client, from within a Vortex script. (Note that although the scripts are nested, the Javascript code is being sent to the client browser for execution: neither Vortex nor the web server actually executes it.)
The problem is both Vortex and Javascript use <SCRIPT> tags to delimit their syntax, and these can't be nested. The end tag for the Javascript is interpreted as the premature end of the Vortex script to the Vortex compiler. The solution is to escape the Javascript's tags in Vortex:
<SCRIPT LANGUAGE=vortex> <A NAME=sendjava msg> <VERB NOESC><SCRIPT LANGUAGE=Javascript></VERB> function submitForm() { theValue = document.forms[0].elements[0].value; if (theValue == "") { alert('$msg'); return(false); } else return(true); } <VERB NOESC></SCRIPT></VERB> </A> <A NAME=main PUBLIC> <FORM METHOD=post ACTION=$url/login.html ONSUBMIT="return submitForm(this)"> User name: <INPUT NAME=user SIZE=10> <INPUT TYPE=submit> </FORM> <sendjava msg="Please enter your user name."> </A> <A NAME=login PUBLIC> Your user name is: $user </A> </SCRIPT> |
(Run this example. Download the source.)
In this example, the sendjava function emits a short piece of Javascript to check the first input box on a form before submitting, to ensure it's non-empty. This is a common use for Javascript, and it saves hits on the server by performing this check entirely in the user's browser.
We embed the Javascript by escaping the <SCRIPT> tags with < VERB nbsp;NOESC> . Any text in a Vortex script inside a VERB block is uninterpreted by Vortex, up to a close tag. The NOESC flag prevents HTML escapement of such text, which is the default. Thus we manage to print the <SCRIPT> tags.
Note that the rest of the Javascript, except for the <SCRIPT> tags, is not escaped: thus we're still in Vortex mode. We use this to pass a Vortex variable to the script: $msg is simply referenced in the Javascript, which to Vortex is plain text. (We must be careful here to maintain Vortex syntax. Or we could have just escaped the entire Javascript, but then we'd lose the ability to pass in Vortex variables.)
The main function in this script sends a form, with an ONSUBMIT to link the Javascript in the browser. Then it calls <sendjava> to print the Javascript, passing it $msg . This is the message that the user's browser will pop up if they submit the form without entering their user name.
Back: Look and Feel Functions | Next: Generating HTML Forms |