How to pass variable values to JavaScript

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:

<?php
$valueFromPhp=’pass value’;
?>

<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.
 

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: