a quick tutorial on javascript variable passing

14
AQ u ick Tu tori a l on J av aScri p t V a ri a b l e P a ss i n g B y  Joe Burns O ne of t he bi g q ue st i on s pe op l e h ave i s how t he y can c arr y i nf orm at i onacr oss p ages. U ser A m ake s a cho i ce o n o ne pa ge an d t hen go es to ano t he r. H ow can I "r emember" w ha t hi s o r he r cho i ce w as? Well, t hebe st w ay is t o se t a co o ki e .  The co o ki e i s p lac e d ri g h t ontheus er' s co m pu t e r an d c a n be r ec al l e d a ga i n and ag a in. I have a t ut ori a l o n d oi n g j us t t ha t ri g ht here . T he probl em i s t ha t m an y p eo pl e ar e sca r ed of coo ki es. T he y d on ' t l i ke t he m an d f ee l t he y' re an i nva si on of t he i r pri vac y. O K , ne . S o n ow ho wdoI get i nf or m ati on acr oss pa ge s? Well, youcoul d d o it t hr ou gh on e p ag e s pa w ninganother, t he n an ot he r, the n a no ther. T ha t w o uld all ow Ja va S cr i pt va ri a b l es t o betra ns f e r re d , b u t t h a t op en s a lot of w ind o w s. To a t t e m pt t o s o l ve t hi s l i t t l e d i l e mm a , I o e r t h i s d o w n a n d d irt y Ja va S cri p t me t h o d . Try t h is: Type you r r st name:  Type your l ast name:  H ow I t W or ks Le t m e star t by sh ow i ng you t he cod e t ha t m ad e t he sm al l f or m j ust ab ove: <FO R M M E TH O D =" LI N K " A C TI O N =" j spas s2. ht m l "> Type your r st name: <I N P U T T Y P E ="text" N A M E =" F irst N am e"> Type y our l ast nam e: <I N P U T T Y P E =" t ext " N A M E =" Last N am e" > <I N P U T T Y P E =" subm i t " VA LU E =" C l i ck and S ee" > </FO R M> Look r st at the m ai n F O R M t ag. Th e ME T H O Dis set t o L I N K and t heA C TI O Nsi m pl y poi nts t ow ard another page. N ow her e in t he r e d oe s i t say t o send the us er inf orm ati on an yw he re. Whe n yo u s et up the f orm i n t hi s m an ne r, w hat t he us er i np uts i s carr i e d a l on g i n t he U R L. T he i nf or m at i oni s se pa rat ed f r om t he act ua l ad dr ess by a qu estionm ar k so it do esn ' t ha r m t he m ovemen t t o anot he r pa ge . T h is li t tle q uir k o f t h e brow se r a llow s u s t o go t o a t ot a ll y n ew pa g e and ca rr y t h e u se r' s i npu t ri g h t a l o n g w i t h usin t h e URL. P r et t y cl eve r, no? N ow al l we ha ve t o d o i s n d a m etho d o f extr ac t i ng t ha t inform at i on f rom t heURL. L i m i tat i o n s N ow m i gh t be a da rn go odtime to di scu ss l i m i t ati on s t o thi s p r oc ess . To be gi n w i t h, t h e in f orm a ti o n is n ot save d aft e r e ac h sur n g like i t i s w ith a co o ki e. I n or de r f or t his t o w o r k, yo u m us t ensur e theus er m ove s in ali ne ar fashi on . R eturni ng and ba cki ng up ca n ha rm t h e i nf orm ation be i ng ca rri ed . N ext, t he w ay I ha ve t hi s se t up , you ca n o nl y t ran sf er t w o var i ab l es f r om pa ge t o p ag e. Y ou ' l l se e w hy i n am omen t . Al so , t h e m e t h o d I h av e w ri t t e n h e re isn't ve ry frie n d l y to sp ace s. I f t h e u se r p u t s a sp a ce i n e i t h e r o f th e ir t wo t ex t b ox e s, t h a t sp a ce w ill b e rep l a ce d b y a p lu s si g n . If yo u 're g o in g t o ac ce p t sp a ce s, yo u 'll e i t h er h ave t o l ive w i t h t h a t or w rite so m e e xt ra co d e t o e l i m i n a t e i t . I n a d d iti o n, t h i s i s d o n e wi t h Ja va S cri p t sot h e r e a r e b r o w se r s t h a t w i l l n o t b e a b l e to p l ay w it h it. T h i s c o d e w a s w ri t t e n i n Ja va S cript 1.0, w hich w a s t h e st a n d a r d w h e n t h i s a r t icle w a s w rit t e n (20 0 5 ), b u t it still w o rks! A s o f Jun e , 2 0 08, t he la t e st ve r si o n o f Ja va S cri pt i s ve rsi o n 1. 9 . I sa w a s ug g es t ionon do in g t h i s by se tti n g t h e a n sw ers t o a n arr ay. T h e a rr ay meth o d al l o w s f o r e n dl e ss va r i a b l es be i ng pa sse d , bu t o l de r b r ow se r s w o u l d n ot be ab l e t o u se i t p r o p e r l y. M y ve r si on al l o w s f or t h e m os t nu m be r of brow se rs t o b e a bl e to p l ay w it h t he cod e b ut on l y us es t w o va r i ab l es. Y o u d ec i de . Click and See

Upload: yan-yan-enriquez

Post on 17-Feb-2018

241 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: A Quick Tutorial on JavaScript Variable Passing

7/23/2019 A Quick Tutorial on JavaScript Variable Passing

http://slidepdf.com/reader/full/a-quick-tutorial-on-javascript-variable-passing 1/14

A Quick Tutorial on JavaScript Variable PassingBy Joe Burns

One of the big questions people have is how they can carry information across pages. User A makes a choice on one page

and then goes to another. How can I "remember" what his or her choice was? Well, the best way is to set acookie. The

cookie is placed right on the user's computer and can be recalled again and again. I have a tutorial on doing just thatright

here.

The problem is that many people are scared of cookies. They don't like them and feel they're an invasion of their privacy. OK,

fine. So now how do I get information across pages? Well, you could do it through one page spawning another, then another,

then another. That would allow JavaScript variables to be transferred, but that opens a lot of windows.

To attempt to solve this little dilemma, I offer this down and dirty JavaScript method. Try this:

Type your first name: 

Type your last name: 

How It Works

Let me start by showing you the code that made the small form just above:

<FORM METHOD="LINK" ACTION="jspass2.html">

Type your first name: <INPUT TYPE="text" NAME="FirstName">

Type your last name: <INPUT TYPE="text" NAME="LastName">

<INPUT TYPE="submit" VALUE="Click and See">

</FORM>

Look first at the main FORM tag. The METHOD is set to LINK and the ACTION simply points toward another page. Nowhere

in there does it say to send the user information anywhere. When you set up the form in this manner, what the user inputs is

carried along in the URL.

The information is separated from the actual address by a question mark so it doesn't harm the movement to another page.

This little quirk of the browser allows us to go to a totally new page and carry the user's input right along with us in the URL.

Pretty clever, no? Now all we have to do is find a method of extracting that information from the URL.

Limitations

Now might be a darn good time to discuss limitations to this process.

To begin with, the information is not saved after each surfing like it is with a cookie. In order for this to work, you must ensure

the user moves in a linear fashion. Returning and backing up can harm the information being carried.

Next, the way I have this set up, you can only transfer two variables from page to page. You'll see why in a moment.

Also, the method I have written here isn't very friendly to spaces. If the user puts a space in either of their two text boxes, that

space will be replaced by a plus sign. If you're going to accept spaces, you'll either have to live with that or write some extra

code to eliminate it.

In addition, this is done with JavaScript so there are browsers that will not be able to play with it. This code was written in

JavaScript 1.0, which was the standard when this article was written (2005), but it still works! As of June, 2008, the latest

version of JavaScript is version 1.9. I saw a suggestion on doing this by setting the answers to an array. The array method

allows for endless variables being passed, but older browsers would not be able to use it properly. My version allows for the

most number of browsers to be able to play with the code but only uses two variables. You decide.

Click and See

Page 2: A Quick Tutorial on JavaScript Variable Passing

7/23/2019 A Quick Tutorial on JavaScript Variable Passing

http://slidepdf.com/reader/full/a-quick-tutorial-on-javascript-variable-passing 2/14

Get The First Name

OK, since you've obviously chosen my method (or else you probably wouldn't be reading this far), let's look at the code that

grabs the first name. This code will be found on the page that the form above IS GOING TO.

<FORM NAME="joe">

<INPUT TYPE="hidden" NAME="burns"></FORM>

<SCRIPT LANGUAGE="javascript">

var locate = window.location

document.joe.burns.value = locate

var text = document.joe.burns.value

function delineate(str)

{

theleft = str.indexOf("=") + 1;

theright = str.lastIndexOf("&");

return(str.substring(theleft, theright));

}

document.write("First Name is " +delineate(text));

</SCRIPT> 

I'm going to tell you what the hardest part of this process is. It kept me at bay for a good hour. I knew the easiest method to

doing this was to use substring JavaScript commands and grab elements from the URL. I also knew I could grab the URL of

a page simply by using the command window.location. Here, this is the URL of this page using the command:

http://www.htmlgoodies.com/beyond/javascript/article.php/3471111/A-Quick-Tutorial-on-JavaScript-Variable-Passing.htm

No sweat right? There's the text string. Just grab what you want. The problem is...that display is not a text string. It's a

property and that means it cannot be acted upon like a text string. Oh that drove me nuts. Once I figured out how to get it

from a property to a text string I was fine. Let's look at that part first.

OK, JavaScript friends, I know there are other ways of doing this, this is just how I like to do it. The code starts with this:

<FORM NAME="joe">

<INPUT TYPE="hidden" NAME="burns">

</FORM>

You may remember that little blip of code for any number of forms you put together. It's basically a text box, but it's hidden.

See how the type is "hidden"? That's a great little trick to give yourself a place to store a value where no one can see it.

I figured if I take the property of the page's location and put it in a text box, the property then becomes the value of that text

box. When you grab the value from a text box it becomes...you guessed it...a text string. Let's look at the Script:

var locate = window.location

document.joe.burns.value = locate

var text = document.joe.burns.value

Page 3: A Quick Tutorial on JavaScript Variable Passing

7/23/2019 A Quick Tutorial on JavaScript Variable Passing

http://slidepdf.com/reader/full/a-quick-tutorial-on-javascript-variable-passing 3/14

That is the beginning blip of code that changes the location into a text string. The property "window.location" is given to a

variable named "locate". Then the value of locate is put into the text box represented by document.joe.burns.value. See that

above? The NAME of the form itself is "joe", the NAME or the hidden text box is "burns". By adding "value" to the end of the

hierarchy statement, I basically forced a value into the box.

The next line grabs that value right back out of the hidden text box and assigns the variable name "text" to it. The location of

the page is now a text string and ready to be broken into parts.Let's say it looks like this:

http://www.server.com/jspass2.html?FirstName=Super&LastName=Man

In order to grab things out of this line of code, we need to look for key elements looking from left to right and later, right to

left. In the example above, we want the text "Super" yanked out of this line of letters.

The keys would most likely be the equals sign (=) it's the first one counting from the left. The ending key would be the

ampersand (&). Again, it's the first one looking from the left. That bookends the text, so let's set up a JavaScript that knocks

everything off including that equals sign, and keeps the next letters until an ampersand shows up. It's not too hard.

function delineate(str)

{

theleft = str.indexOf("=") + 1;

theright = str.lastIndexOf("&");return(str.substring(theleft, theright));

}

document.write("First Name is " +delineate(text));

First a function, named delineate(), is set up that will look for certain things.

The variable "theleft" is given the value of the first instance of an equals sign reading from the left. That's what indexOf()

does. Notice we add one because we don't want the equals sign. Adding one skips it. Notice that each line is acting upon

something called "str". At the moment "str" has no value. We'll pass it a value in the last line.

Next, the variable "theright" is given the value of looking for the first instance of & reading from the right. That's what

lastIndexOf() does.

So now we have our bookends set. Let's grab the text. The next line returns the substring of what appears between theequals sign (theleft) and the & (theright). See that?

Finally, the value is grabbed using a document.write command. Remember that at this point, nothing has actually been done.

The document.write statement actually triggers the function to run. But look! When the function is triggered to run, now it is

being passed a new variable, "text". That's the text string of the location to be acted upon.

The return is the text Super.

Grab The Last Name

Grabbing the last name is a whole lot easier. If you look at the text string again, you'll see we only need to set one point to

look for. There's nothing following the last name so if we read from the right and basically chop off everything including the

second equal sign (from the right it's the first), then we'll be left with the last name. Here's the code that did it.

var locate = window.location

document.joe.burns.value = locate

var text = document.joe.burns.value

function delineate2(str)

{

point = str.lastIndexOf("=");

Page 4: A Quick Tutorial on JavaScript Variable Passing

7/23/2019 A Quick Tutorial on JavaScript Variable Passing

http://slidepdf.com/reader/full/a-quick-tutorial-on-javascript-variable-passing 4/14

return(str.substring(point+1,str.length));

}

document.write("Last Name is " +delineate2(text));

The code is very much the same in that it grabs the window.location and turns it into text. Where it differs is that the text

string is only searching, from the right, for one item, the second equal sign.

The variable "point" is given the job of representing everything up to the second equal sign (first from the right - note I usedlastIndexOf()).

The return is that point plus one, again to not include the equal sign, and then the length of the string - that's everything that

follows and that's the last name.

A document.write statement again triggers the function and passes the variable "text" to it.

Placing the Value

At this point in time you can place the value anywhere you want by using the document.write where ever you want. I have

some text thrown in but that's easily taken out. Remember to remove the plus sign if you take the text out. Getting the name

into a text box is actually pretty easy. Here's the code I used on the example page.

<FORM NAME="bull">

Last Name: <INPUT TYPE="text" NAME="bear">

</FORM>

<SCRIPT LANGUAGE="javascript">

var zork = delineate2(text)

document.bull.bear.value = zork

</SCRIPT>

You might notice a big chunk of it from the other scripts. I created a box first. The box has to be first or the hierarchy

statement won't run. Error. The box is visible this time around. The value of the function is assigned to the variable "zork"

and then zork is put into the text box. Pretty straightforward.

Just remember to change out the NAMEs of each element if you put more than one text box on a page. You also have tocome up with a different variable name for the second text box. In other words you can't have two zorks on the same page.

That's That

And speaking of two zorks on the same page, remember the limitations of this. You can carry the same info across many

pages, but they all must be in order. If you take these variables to yet a third page, all this coding must be redone on the new

page. The variable does not carry across pages. The text in the URL carries. Once it gets to the new page, it has to be

assigned a new variable...each time.

<!DOCTYPE html>

<html>

<body>

Page 5: A Quick Tutorial on JavaScript Variable Passing

7/23/2019 A Quick Tutorial on JavaScript Variable Passing

http://slidepdf.com/reader/full/a-quick-tutorial-on-javascript-variable-passing 5/14

<p>Click the button to call a function with argument<p>

<button onclick"#my$unction%&'a((((up&)&'i(ard&*#>Try it<button>

<cript>

function my$unction%name)+ob*

,

alert%#'elcome # - name - #) the # - +ob*.

/

<cript>

<body>

<html>

Output

Click the button to call a function with arguments

[Try it] //button

<html>

<head>

</head>

<body>

<div align="center">

<form name="nameTemp">

First Name: <input name="firstName" type="text"><br>

ast Name: <input name="lastName" type="text">

</form>

<form name="mainForm" onsubmit="return singleName!this">

age: <input name="age" type="text" value="#$"><br>

gender: <input name="gender" type="text" value="male"><br>

sex: <input name="sex" type="text" value="yes"><br>

<input name="firstast" type="hidden">

Page 6: A Quick Tutorial on JavaScript Variable Passing

7/23/2019 A Quick Tutorial on JavaScript Variable Passing

http://slidepdf.com/reader/full/a-quick-tutorial-on-javascript-variable-passing 6/14

<input type="submit">

</form>

</div>

<script type="text/%avascript">

function singleName!form

&

if !document'nameTemp'firstName'value == ((

&

alert!()lease enter your first name'(*

document'nameTemp'firstName'focus!*

return false*

+

if !document'nameTemp'lastName'value == ((

&

alert!()lease enter your last name'(*

document'nameTemp'lastName'focus!*return false*

+ else &

form'firstast'value = document'nameTemp'firstName'value ,

document'nameTemp'lastName'value*

+

return true*

+

</script>

</body>

</html>

2007-02-09: Your JavaScript page has retrieved some information from the user.

Now you want to display another JavaScript page, which should also use that

information. How do you pass it from the first page to the second? There are

three simple solutions. The first two are safe and effective, with advantages

and disadvantages to each. The third appears ideal but has avery serious

security problem and should be avoided.

1. Submitting form data to a server-side script that then outputs a new

JavaScript page containing the data. This is simple and reliable and works in

all browsers, but requires support for server-side scripting of some kind (PHP,

ASP, etc).

Page 7: A Quick Tutorial on JavaScript Variable Passing

7/23/2019 A Quick Tutorial on JavaScript Variable Passing

http://slidepdf.com/reader/full/a-quick-tutorial-on-javascript-variable-passing 7/14

2. Passing form-style data in a URL to a new JavaScript page, without using

any server-side scripts. This works in all browsers but supports a limited

amount of data. It is the traditional way of solving the problem without server-

side scripting.

3. Passing data via thewindow.name property. Although this is not the intended

purpose ofwindow.name, it seems to work quite well and supports larger

amounts of data than the second method. And it works in Safari, Firefox, and

Internet Explorer. So why not use it? Because it ishighly insecure! If the user

follows a link toanother website that doesn't belong to you, that other website

canstill see the data stored inwindow.name, which was never meant to be a

secure, site-specific property. So I strongly discourage the use of this method.

When possible, it's best to use the first method, because the amount of data

you can pass is essentially unlimited. I'll demonstrate the first two methods

and give an overview of the third, but as I said, the third is unsafe and you

should not use it.

1. Using a Server-Side Script

When server-side scripting is available, this is the best approach. Let's

assume you have a JavaScript array of strings you'd like to pass to a new web

page:

<script>var data = new Array();data[0] = "one, a datum";data[1] = "two, a deer";data[] = "t!ree, a sas!# $$";data[%] = "&our !as 'uotes# $" &oret w!at &our was &or$"";<*script>

To pass this array to a script on a new page without packing it into a long URL

(remember,URLs are limited to a practical maximum of 2,083 characters in

the most popular web browser, and long URLs don't look very pretty either),

we can use a hidden form in the first page, and submit this form to a PHP

script on the server using the POST method. The GET and POST methods

Page 8: A Quick Tutorial on JavaScript Variable Passing

7/23/2019 A Quick Tutorial on JavaScript Variable Passing

http://slidepdf.com/reader/full/a-quick-tutorial-on-javascript-variable-passing 8/14

differ in that a GET-method form submission packs everything in the URL,

which is nice for bookmarkable searches but a poor choice for large amounts

of data. The POST method submits the data outside of the URL, without a

length limit.

You could call the sendData function from any JavaScript code. Calling it

when a link is clicked is simply one example.

We'll use a hidden field in the hidden form to pass the information. A hidden

form field is a single string, so we'll pack the array into it by using a comma to

separate elements of the array. And since the data might also contain

commas, we'll use JavaScript'sescape() function to encode these, so that they

can't be confused with our separators. We'll name both the form and the

hidden field within itdata. When we do this, we access set the contents of the

hidden field using the JavaScript syntaxdocument.data.data.vaue (read from

right to left: the value of the field named data, in the form named data, in the

document).

Want to test this technique on your own computer? You'll need a web server

with PHP support on your computer. PHP can't be tested on your local hard

drive, because PHP is a server side solution. SeeHow do I test PHP, ASP,

server side include and CGI pages offline or at home?

The two listings that follow

arepassdata1a.!tm andpassdata1+.p!p.passdata1a.!tm passes an array of

JavaScript data topassdata1+.p!p when a link is clicked.

 passdata1a.html

<script>var data = new Array();data[0] = "one, a datum";data[1] = "two, a deer";data[] = "t!ree, a sas!# $$";data[%] = "&our !as 'uotes# $" &oret w!at &our was &or$"";<*script><&orm name="data" met!od="-/" action="passdata1+.p!p"><input type="!idden" name="data">

Page 9: A Quick Tutorial on JavaScript Variable Passing

7/23/2019 A Quick Tutorial on JavaScript Variable Passing

http://slidepdf.com/reader/full/a-quick-tutorial-on-javascript-variable-passing 9/14

<*&orm><script>&unction sendata()  ** nitiai2e pac3ed or we et t!e word 4unde&ined4  var pac3ed = "";  &or (i = 0; (i < data.ent!); i55)   i& (i > 0)   pac3ed 5= ",";  6  pac3ed 5= escape(data[i]);  6  document.data.data.vaue = pac3ed;  document.data.su+mit();6<*script><!1>/!is is w!at t!e array contains#<*!1><u><script>  &or (i = 0; (i < data.ent!); i55)

  document.write("<i>" 5 data[i] 5 "<*i>$n");  6<*script><*u><a !re&="7avascript#sendata();">8o to passdata1+.p!p<*a>

 passdata1b.php

<9p!p  :pac3ed = :-/[4data4];  :data = spit(",", :pac3ed);  &or (:i = 0; (:i < count(:data)); :i55)   ndo w!at avacript4s escape() &unction did

  :data[:i] = rawurdecode(:data[:i]);  as!es need escapin w!en t!ey appear in code  :data[:i] = strrepace("$$", "$$$$", :data[:i]);  ?uotes need escapin too  :data[:i] = strrepace("$"", "$$$"", :data[:i]);  69><script>  var data = new Array (<9p!p  &or (:i = 0; (:i < count(:data)); :i55)   i& (:i > 0)   ec!o ",$n";  6  ec!o " $"";  ec!o :data[:i];  ec!o "$"";  69>

  );<*script><!1>/!is is w!at t!e data contains#<*!1>

Page 10: A Quick Tutorial on JavaScript Variable Passing

7/23/2019 A Quick Tutorial on JavaScript Variable Passing

http://slidepdf.com/reader/full/a-quick-tutorial-on-javascript-variable-passing 10/14

<u><script>  &or (i = 0; (i < data.ent!); i55)   document.write("<i>" 5 data[i] 5 "<*i>$n");  6<*script><*u>

2. Using JavaScript Only: Data in the URL

When server-side scripting is not available, it is still possible to pass data

between web pages, either via the "query string" (the portion of the URL after

the ?) or thewindow.name property. First we'll look at how to do it via the query

string.

The main problem with the query string approach is that the amount of datayou can pass is limited.The maximum total safe length of a URL is 2,083

characters, and "escaping" of data like whitespace and punctuation will

consume quite a bit of this space. So this technique should be used only for

small amounts of information. For larger amounts, use the PHP technique

demonstrated above a similar technique based on ASP or Perl, or

thewindow.name technique at the end of this article. Just keep in mind that

server-side scripting is always preferable for passing large amounts of data.

Implementing the Query String Solution

When web servers see a URL that specifies an ordinary HTML web page,

followed by a9 character, followed by additional data, like this:

!ttp#**[email protected]*pae.!tm9t!is0is0some0data

They deliver the file*pae.!tm to the browser and ignore the9 and the data

beyond it. However, this datais available to JavaScript code inpae.!tm, in

the variablewindow.ocation.searc!.

Even though this technique uses only JavaScript, youcannot test this using

two HTML pages on your own hard drive in Internet Explorer unless you

have a web server on your own computer -- a simple and useful thing to have,

Page 11: A Quick Tutorial on JavaScript Variable Passing

7/23/2019 A Quick Tutorial on JavaScript Variable Passing

http://slidepdf.com/reader/full/a-quick-tutorial-on-javascript-variable-passing 11/14

and I recommend setting one up for testing purposes. Test this technique with

your pages on a web server, not just your hard drive. Or test it in Firefox,

which allows URLs with a ? to work correctly for JavaScript pages on the local

hard drive.

Again, let's assume you have a JavaScript array of strings you'd like to pass to

a new web page:

<script>var data = new Array();data[0] = "one, a datum";data[1] = "two, a deer";data[] = "t!ree, a sas!# $$";data[%] = "&our !as 'uotes# $" &oret w!at &our was &or$"";<*script>

We can pass this data to a second page by packing the array into a single

string, "escaping" each of the array elements with

JavaScript'sescape() function and then separating them with commas. We

then send the browser to a new page by

settingwindow.ocation topassdata+.!tm (the name of the new page), followed

by a9 character, followed by our packed string. In the second page, we'll find

the data inwindow.ocation.searc! and break it back into separate array

elements with thespit()function, and then useunescape() to restore each ofthese elements to their normal appearance.

The two listings that follow

arepassdataa.!tm andpassdata+.!tm.passdataa.!tm passes an array of

JavaScript data topassdata+.!tm when a link is clicked.

 passdata2a.html

<script>

var data = new Array();data[0] = "one, a datum";data[1] = "two, a deer";data[] = "t!ree, a sas!# $$";data[%] = "&our !as 'uotes# $" &oret w!at &our was &or$"";<*script><script>&unction sendata()  ** nitiai2e pac3ed or we et t!e word 4unde&ined4

Page 12: A Quick Tutorial on JavaScript Variable Passing

7/23/2019 A Quick Tutorial on JavaScript Variable Passing

http://slidepdf.com/reader/full/a-quick-tutorial-on-javascript-variable-passing 12/14

  var pac3ed = "";  &or (i = 0; (i < data.ent!); i55)   i& (i > 0)   pac3ed 5= ",";  6  pac3ed 5= escape(data[i]);  6  window.ocation = "passdata+.!tm9" 5 pac3ed;6<*script><!1>/!is is w!at t!e array contains#<*!1><u><script>  &or (i = 0; (i < data.ent!); i55)   document.write("<i>" 5 data[i] 5 "<*i>$n");  6<*script><*u><a !re&="7avascript#sendata();">8o to ae /wo<*a>

 passdata2b.html

<script>  var 'uery = window.ocation.searc!;  ** 3ip t!e eadin 9, w!ic! s!oud aways +e t!ere,** +ut +e care&u anyway

  i& ('uery.su+strin(0, 1) == 494)   'uery = 'uery.su+strin(1);  6  var data = 'uery.spit(4,4);&or (i = 0; (i < data.ent!); i55)

  data[i] = unescape(data[i]);  6

<*script><!1>/!is is w!at t!e array contains#<*!1><u><script>  &or (i = 0; (i < data.ent!); i55)   document.write("<i>" 5 data[i] 5 "<*i>$n");  6<*script><*u>

3. Using JavaScript Only: window.name

The query string solution is the traditional way to pass data without server sidescripting, but it supports a limited amount of data. Recently another alternative

has gained popularity: thewindow.name property.

The original purpose ofwindow.name is not to pass data between pages. The

idea is that a browser window (or tab) can be given a name that can then be

Page 13: A Quick Tutorial on JavaScript Variable Passing

7/23/2019 A Quick Tutorial on JavaScript Variable Passing

http://slidepdf.com/reader/full/a-quick-tutorial-on-javascript-variable-passing 13/14

used to refer to that window later. For instance, thewindow.open function can be

used to open a new page in an existing popup window by specifying its name.

However, clever programmers have noticed that thewindow.name property can

be changed by JavaScript code and has no apparent fixed length limit. So whynot use it to pass data between pages?

There are three downsides to this approach. The first two have simple

workarounds, but the third is afatal security flaw:

A. Internet Explorer rejects special characters inwindow.name. So you can't trust

line breaks (carriage returns) or binary data to stick around inwindow.name. We

handle this issue the same way we handle it for the query string: by "escaping"our data.

B. If you are usingwindow.name to pass data around, then you no longer have

the option of using it to refer to the window inwindow.open calls and so on. You

could work around this by removing the data fromwindow.name after you parse

it, but then the data is no longer available if the user reloads the page.

Depending on your needs, this may or may not be a serious issue for your

purposes.

C. Once the data is inwindow.name, it stays there even if the user follows a link

to acompletely different website. This is extremely dangerous - especially if

there is personal information included in the data! Please do not use this

method.

A few developers may feel thatwindow.name is safe for use in their application

because there will never be any personal information passed. This is almost

always a mistake - you don't know how users will choose to use your webapplication, and what they will hold you responsible for if things go badly

wrong.

If you do choose to usewindow.name to pass data, note that

thewindow.name property is not available to JavaScript code that executes while

Page 14: A Quick Tutorial on JavaScript Variable Passing

7/23/2019 A Quick Tutorial on JavaScript Variable Passing

http://slidepdf.com/reader/full/a-quick-tutorial-on-javascript-variable-passing 14/14

the page is still loading. You will need to access it from a function called by

theonBoad handler of the+ody element.