Services · Blog · Demo
Get on the scene
26 Sep 2007 – 20:14 in by Crawford Currie
Getting the values of TWiki variables into Javascript can be a trial. This article describes one simple technique for doing that.
Transferring the values of TWiki variables into Javascript. It's no problem if you write your Javascript inline, but that will soon become impossible if security settings are enabled on the server. You could always write a REST handler to drag the values over from the server using a XmlHttpRequest – but that's like using a sledgehammer to swat flies.

What's really needed is a simple methodology for making the values of selected TWiki variables available to Javascript.

The problem is that while TWiki variables are expanded in templates, unless your Javascript is inline there is no way of getting that value into the Javascript. For example, let's take a simple example; we have an input, and we want to invoke a validator on it:

<script src="%PUBURL%/%SYSTEMWEB%/MyPlugin/validator.js"></script>
<input type="text" value="Urgh" onchange="javascript:validateInput()">

The validator is in a Javascript file called validator.js

function validateInput() {
   var url = '%SCRIPTURL{rest}%/MyPlugin/Validate';
   ... perform an XmlHttpRequest to get the value validated...
}
The problem is that there is no way to expand %SCRIPTURL{rest}% inside validator.js. Somehow we have to pass this value to the Javascript.

The easiest way to do this is in the DOM. And HTML generously gives us the META tag that we can use as we see fit. So in our plugin, we can write:

TWiki::Func::addToHEAD('MYPLUGIN', '<META name="MyPluginData" value="%SCRIPTURL{rest}%">');

Now we change validator.js as follows:

function validateInput() {
   var meta = document.getElementsByTagName('META');
   for (var i = 0; i < meta.length; i++)
      if (meta[i].name == 'MyPluginData') {
         scripturl = meta[i].value;
         break;
      }
   var url = scripturl + '/MyPlugin/Validate';
   ... perform an XmlHttpRequest to get the value validated...
}

Oviously if you are passing a number of values, it makes sense to do the search of the META tags once and build a hash of the values.

If you can'y write to the header for some reason, you can also use other (body) tags to perform a similar trick, and stop them being displayed using style='display:none'


Leave a Reply

You may have to login or register to comment if you haven't already.
r1 – 26 Sep 2007 – 20:43:48 – Main.CrawfordCurrie
Copyright © 1999-2008 WikiRing Partnership – Contact us