Declare a variable in a URL and assign it a value in Javascript when navigating to a page

HashFail picture HashFail · Feb 2, 2013 · Viewed 9k times · Source

I'm relatively new to HTML (and programming in general), and I'm trying to declare a variable and assign it a value when I navigate to a page. What I have is a line of code like this:

function() navigate {window.location = "myPage.html?myVar=1";}

When I run the function, the new page will load, but whenever I try to access the variable, I get an error saying the variable is undefined. However, if I define the variable in the new page, for example <script>var myVar;</script>, the value is set to null rather than the value that I try to set it to in the navigate function I used earlier.

I can't think of any solution to this, and my error probably stems from my misconceptions about how the ? at the end of the url works, but I can't find a good explanation of how it works anywhere.

Answer

Bassam Mehanni picture Bassam Mehanni · Feb 2, 2013

The query string variables are intended for passing data to the server when we request a page, however you could still access them using javascript, checkout this Stackoverflow question How can I get query string values in JavaScript?