RSS
 

Passing Variables

19 Jan

gearsAs a direct marketer I often find myself in the position where we need to pass data from one page to the next. The problem is with many vendors they do not allow you direct access to the source code for dynamic pages. The workaround that we have used for many clients is to pass variables from page to page using the query string (URL) and JavaScript.

I’ve included a code snippet that makes this easy and some examples of how you can use the data once passed.

First, you need to add the variable array function to the top of your page. This block should be above where you are trying to insert the code (typically the head tag is the best place)

01
<script type="text/javascript"><!-- 
02
    function getQueryVariable(variable) {
03
      var query = window.location.search.substring(1);
04
      var vars = query.split("&");
05
      for (var i=0;i<vars.length;i++) {
06
        var pair = vars[i].split("=");
07
        if (pair[0] == variable) {
08
          return pair[1];
09
        }
10
      }
11
    }
12
     // --></script>

Now once you have the function in place you can call any variable from your URL string. In this case we will use the variable “x” where the URL string would look something like… www.yoursite.com/index.php?x=Hello

In the first example we will just write the data directly to the page:

1
<script type="text/javascript"><!--
2
 
3
      document( getQueryVariable("x") );  
4
// --></script>

You can also have the variable populate a field value in a form. In the case below you would need to provide the formname and fieldname that you would like to update:

1
<script type="text/javascript"><!--
2
 
3
      document.formname.fieldname.value =  getQueryVariable("x");  
4
// --></script>

In this last example we demonstrate how you can use the query string to do simple math equations. In this example we pass the most recent gift (MRG) through the URL string and it calculates suggested donations levels from the MRG. If MRG is left blank we auto populate the donation field with default values:

01
<script type="text/javascript"><!--
02
 
03
var level1 = getQueryVariable("mrg") /2 ;
04
var level2 = getQueryVariable("mrg");
05
var level3 = getQueryVariable("mrg") *2 ;
06
var level4 = getQueryVariable("mrg") * 4;
07
 
08
if(level1=="") {
09
 
10
	level1 = "25";
11
	}
12
 
13
if(level2=="") {
14
 
15
	level2 = "50";
16
	}
17
 
18
if(level3=="") {
19
 
20
	level3 = "100";
21
	}
22
 
23
if(level4=="") {
24
 
25
	level4 = "250";
26
	}
27
// --></script>

No related posts.

 
1 Comment

Posted in Code

 

Tags: , ,

Leave a Reply

 
 
  1. Adam

    September 19, 2009 at 2:05 am

    Hey Matt,
    Thanks for explaining this in such an easy to understand way!
    Is it possible to populate all the variables into one form field to create a sentence (with spaces between variables).
    ie: getQueryVariable(“x+y+z”)

    to get result:
    x y z