Saturday, 29 March 2014

How to get querystring value from url using - JS - jquery

Problem definition

http://www.raymn.in/index.php?username=rahul&password=123

In above link querystring is username=rahul&password=123 and the values are rahul and 123.

So we have to extract values from url. how??

Solution

Step by Step description,
First Step: Get querystring from URL.. var sPageURL = window.location.search.substring(1);

var sPageURL holds "username=rahul&password=123"

Second Step: Split queries from "&".. var sURLVariables = sPageURL.split('&');

sURLVariables is array of "username=rahul" and "password=123"

Third Step: Split values from "="..var sParameterName = sURLVariables[i].split('=');

sParameterName holds array of "username", "rahul", "password", "123"

Example
//JS example
function getQueryStringParams(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) 
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) 
        {
            return sParameterName[1];
        }
    }
}​

//JQuery example
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var array = [], values;
    var arrayOfQuery = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < arrayOfQuery.length; i++)
    {
        values = arrayOfQuery[i].split('=');
        values.push(values[0]);
        vars[values[0]] = values[1];
    }
    return array;
}


Tags and Related Topics
Parse query string in JavaScript,
jquery get querystring from URL,

No comments:

Post a Comment