How to pass variable values to JavaScript

May 22, 2009 – 3:45 pm 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.

Share this:

RSS feed Subscribe to my RSS feed

About the author

Jani is a 15 year veteran of the software industry. He's currently available for consulting

  1. 16 Responses to “How to pass variable values to JavaScript”

  2. Another approach would be to actually just embed the data in the page in your HTML, possibly using Microformats or other semantic technologies.

    By Ciaran McNulty on May 22, 2009

  3. Another one would be to use meta tags in the head like this:

    …and then check the values like this:

    var foo = $(‘meta[name="foo"]‘).attr(‘content’);

    By Bohdan Ganicky on May 22, 2009

  4. oops…I mean:

    meta name=”foo” content=”bar”
    meta name=”baz” content=”asd”

    By Bohdan Ganicky on May 22, 2009

  5. What about JSON? That’s the defacto standard for information interchange with JavaScript. PHP (which is used in the first example) even has native JSON encoding and decoding functionality.

    By Elijah Grey on May 22, 2009

  6. Yet another approach:

    PS. parsing URL in Javascript can be tricky because of URL URI translation in .htaccess or MVC controller…

    By Orkan on May 24, 2009

  7. Oops, my previous example has gone. A lighter version:

    script src=”scriptaculous.js?load=effects,dragdrop” type=”text/javascript”

    By Orkan on May 24, 2009

  8. I think I need to find a WordPress plugin that will allow you guys to paste code to comments easier. Any suggestions?

    By Jani Hartikainen on May 24, 2009

  9. how do i use the value of javascript variable that i pass as argument in a function?

    By Girish on Jun 29, 2009

  10. You can also get your variables via AJAX or AJAJ after document.onload

    By sokzzuka on Jun 29, 2009

  11. This can also be useful :
    passing value from javascript to php

    By Satya Prakash on Sep 2, 2009

  12. Can you please explain this line of code:

    pairs[pair[0]] = pair[1];

    By Paul Lohr on May 23, 2011

  13. Since the code is splitting values from the URL, such as myparam=myvalue, the pair variable contains an array with a key and a value.

    The line you show is simply assigning the value into the pairs object with the correct key – sort of like using an associative array in PHP if you’re familiar with that.

    It might be easier to understand if you try the code yourself.

    By Jani Hartikainen on May 24, 2011

  14. 2. Passing variables in URLs

    after returning the pairs how would I pass the pairs to this tag in the page?
    mywebsite

    By Brad on Feb 14, 2012

  1. 3 Trackback(s)

  2. May 22, 2009: 如何传递变量给JavaScript | 航海日志 | Way to OnePiece
  3. May 23, 2009: How to pass variable values to JavaScript | Dailytuts.net
  4. May 30, 2009: How to pass variable values to JavaScript | pc-aras

Post a Comment

You can use some HTML (a, em, strong, etc.). If you want to post code, use <pre lang="PHP">code here</pre> (you can replace PHP with the language you are posting)