How to pass variable values to JavaScript

Tags:

A relatively common task in today’s Web 2.0 apps is passing values from a server-side script (or through a link) to JavaScript, affecting the client-side script execution.

Not surprisingly, there are a few ways to do that. Let’s look at three and their pros and cons:

  • Embedding scripts into templates
  • Passing variables in URLs
  • Using configurable scripts

1. Embedding scripts into templates

This is the most straightforward way of passing values: Embed your JavaScript code into the template/view or whatever you call the thing you’re outputting from your server-side script.

Here’s a PHP example:

<html>
 <head>
  <script type="text/javascript">
   function onload() {
    alert('Value from PHP: <?php echo $valueFromPhp; ?>');
   }
  </script>
 </head>
 <body onload="onload()">
  You'll get an alert with a value from PHP when this page loads
 </body>
</html>

The example shows a very simple function which just alerts a message with a variable’s value.

The pro’s of this approach is of course the simplicity – as long as the script itself is not very complex, this approach is very easy to use and won’t require any special JavaScript coding tricks either.

However, this approach does not lend itself for reusable code. Because your script is written straight into the template, to reuse it elsewhere you need copypasting. Also, with very complex scripts (which are usually also the reusable kind), this does not really work so well.

2. Passing variables in URLs

This is an approach you are probably familiar with from server-side languages: Using GET or POST variables to pass values to scripts.

However, due to limitations of JavaScript, you won’t be able to read POST data using it. Also, it doesn’t have any built in methods for easily accessing GET data either, but it’s possible.

Since JavaScript can see the current page’s complete URL, you can create a script to manually parse the variables you want from the URL.

Here’s a simple approach to extracting get parameters from the URL:

function getQueryParameters() {
  var query = window.location.href.split('?')[1];
 
  //query won't be set if ? isn't in the URL
  if(!query) {
    return { };
  }
 
  var params = query.split('&');
 
  var pairs = {};
  for(var i = 0, len = params.length; i < len; i++) {
    var pair = params[i].split('=');
    pairs[pair[0]] = pair[1];
  }
 
  return pairs;
}

Using the above function, you will get a JS object with each GET parameter showing in the URL, quite similar to $_GET in PHP.

The main benefit of parsing the URL for parameters like this in JS is that you can do stand-alone pages that don’t require interference from a server-side language to set parameters.

3. Using configurable scripts

This is the most advanced approach of the three. It’s similar to #1, as you will need to include some JavaScript code in your template for this.

There are two styles of configuration:

  • Using a global variable, where you define some variable with the configuration parameters for your code, and…
  • Configuring by method calls, where you add some way to your JS code to be configured via creating a new instance of an object or by calling a function

If you have used Dojo, you may be familiar with the first style: With Dojo, you can configure some settings by creating a djConfig variable.

The first approach is easier to use: Your code will simply attempt to read the global variable for the settings, if defined. However, it’s not without it’s problems. As you may have heard, global variables are not a good idea as they can interfere with other scripts and they are easy to accidentally change.

The second approach requires some more thinking when you create your JS code, but it’s the one which makes the JS code easy to reuse and more flexible.

Despite sounding tricky, making your JS code configurable by a function call is relatively simple, but of course not as simple as inlining the whole script in the template.

The basic idea is to make your code into a JS object, and allow the creation of a new object instance, or calling a function of the object like this:

var configurableObject = {
  someFunc: function() { /* does something */ },
  setOptions: function(config) { /* save configurations from config here */ }
};
 
configurableObject.setOptions({
  foo: 'bar',
  baz: 'asd'
});
 
//Or like this:
var newableObject = function(config) {
  /* save configurations from config here */
};
 
newableObject.prototype = {
  someFunc: function() { /* does something */ }
};
 
var o = new newableObject({
  foo: 'bar',
  baz: 'asd'
});

The main idea of this approach is that you can put your actual JS code into a separate file, and then in your page where you need the code, you include the file with a script tag and add another script tag, which sets up the object with the configuration you need. This way the code is easy to reuse and maintain, as you can use the code anywhere at all because it doesn’t depend on parameters being in the URL, in a global variable or any other such hinderance.

Conclusion

With these three approaches you can do quite a lot. The first is most useful when you just need to get something done quickly, but it isn’t very clean. The second is something in between, but it limits reusability. The method style of the third approach works best especially if you need to be able to reuse the code, but it’s the most complex of them.

There may be some other ways of doing this too, so if you use some other approach, feel free to share it in the comments.