Tuesday, February 12, 2013

Get URL Variables With JavaScript


As most of you probably know, the GET method is a common way for PHP websites to pass nonsensitive information between pages. At some point you may want to access this information dynamically using JavaScript. Luckily, accessing URL variables is rather simple and I will cover the process step by step below.


1. The first thing we need to do is create a demo URL that is using the GET method to test our script.


http://www.procureeminence.com/?title=JoeDirt&keyphrase=Classy



2. Next we can create a blank JavaScript function that will eventually be able to access the URL variables. Let's call the function "GetUrlValue()". We also want the ability to pass the desired URL variable name into the function so let's add the variable "VarSearch" to capture this data.


function GetUrlValue(VarSearch){

}



3. Next we need to get the "Query String". To do this we call the "window" object, access the location object within the window object and then access the search property. This will return a string containing "?title=Classy&keyphrase=NotJoeDirt" which is great except we don't need the "?".


function GetUrlValue(VarSearch){
    window.location.search;
}


      


4. To remove the "?", let's add the "substring()" method and remove the first character by passing 1 as the parameter.


function GetUrlValue(VarSearch){
    window.location.search.substring(1);
}



5. Create a variable called "SearchString" to store the query string.


function GetUrlValue(VarSearch){
    var SearchString = window.location.search.substring(1);
}



6. Now we will split the data up into individual variables (key-value pairs) and store it in an array called "VariableArray". To divide the variables we will use the "split()" method and specify that we want to split the string at every "&" character.


function GetUrlValue(VarSearch){
    var SearchString = window.location.search.substring(1);
    var VariableArray = SearchString.split('&');
}





7. Once we have the array of variables we need to create a "for" loop to scan for the desired variable. Since we are scanning through an array we need the var i to start at 0 because arrays are indexed starting at 0. "i" will be used to access the appropriate array element based on the loop iteration. Next we get the number of array elements stored in "VariableArray" by accessing the "length" property and make sure "i" doesn't reach that value. In our case "VariableArray.length" will equal 2 so the for loop will complete two cycles, once with i=0 and once with i=1 and on the third cycle i will become equal to "VariableArray.length" making the loop stop before the internal code is executed. To make "i" increase by 1 on each cycle we will add "i++" as the third parameter.


function GetUrlValue(VarSearch){
    var SearchString = window.location.search.substring(1);
    var VariableArray = SearchString.split('&');
    for(var i = 0; i < VariableArray.length; i++){

    }
}


8. Now that the for loop is set up we can add the search code. In order to search for the URL variable name we first need to split the key-value pair into another array. Add an array called "KeyValuePair" to store the key-value data from the previous array. To do this lets type the previous array name "VariableArray" and use the "i" variable to select a different array index on each cycle, which should look like this; "VariableArray[i]". Now that the index will be selected dynamically, we can use the "split()" method to separate the data into the new array. We must split the data based on the "=" character by passing it as a parameter; split('='). Please note that on each loop the previous data in the "KeyValuePair" will be overwritten by new data.


function GetUrlValue(VarSearch){
    var SearchString = window.location.search.substring(1);
    var VariableArray = SearchString.split('&');
    for(var i = 0; i < VariableArray.length; i++){
        var KeyValuePair = VariableArray[i].split('=');
    }
}


9. Since the key (aka URL variable name) will always be stored in index 0 of "KeyValuePair" we can use an
"if" statement to check for the matching URL variable name. Add "KeyValuePair" index 0 (KeyValuePair[0]) to the parameter and see if it's equal too (==) the variable name we had passed into the "GetUrlValue()" function, which was stored in the "VarSearch" variable. If the values match we want to return the current value of the key-value pair which will be in index 1 "KeyValuePair[1]". Once the return statement is called, the function will stop and the selected value will be returned. If no match is found the function will execute all the code contained within it and return the value of "undefined". At this point the function is finished and can be seen in its entirety below.

function GetUrlValue(VarSearch){
    var SearchString = window.location.search.substring(1);
    var VariableArray = SearchString.split('&');
    for(var i = 0; i < VariableArray.length; i++){
        var KeyValuePair = VariableArray[i].split('=');
        if(KeyValuePair[0] == VarSearch){
            return KeyValuePair[1];
        }
    }
}

10. To test out the function let's create an alert message that will display the value of our request URL variable. Please see the examples below:

//Alert the value of title
alert(GetUrlValue('title'));
     The output should be "JoeDirt"

//Alert the value of keyphrase
alert(GetUrlValue('keyphrase'));
      The output should be "Classy"

//Alert the value of random
alert(GetUrlValue('random'));
     The output should be "undefined"



Congrats! You have just made a simple function that retrieves URL variables and their values. I hope you enjoyed this tutorial and I look forward to all the comments/suggestions! For all source code, demos and reference material please use the links below.


Resources


References

11 comments:

  1. Its very useful article for us..I am gonna use your blog to improve my skill..
    research methodology

    ReplyDelete
  2. Excelent explanation and function! You just saved me!

    ReplyDelete
  3. Best guide that I have found on this argument

    ReplyDelete
  4. This is a practical example of how to pass a variable to a website using the URL.
    Thank you!

    ReplyDelete
  5. Nice and simple! Thanks for your help!

    ReplyDelete
  6. nice thanks. To read window url, protocol, origin read this post : get current window url in javascript

    ReplyDelete
  7. Very useful! Is there a way to return an empty value (no value) instead of Undefined?

    ReplyDelete
  8. Clear and concise article. Thanks :)

    ReplyDelete