Last Updated: April 27, 2021
·
2.872K
· cachedout

Get current URL parameters as hash (JS)

Hi All,

Today I was working with ajax polling and I found that I needed the GET parameters of my current URL in a hash to pass into the ajax data field.

I wrote a simple function to do this and thought some of you may get some use out of it.

function getUrlParameters() {
    var pageParamString = unescape(window.location.search.substring(1));
    var paramsArray = pageParamString.split('&');
    var paramsHash = {};

    for (var i = 0; i < paramsArray.length; i++)
    {
        var singleParam = paramsArray[i].split('=');
        paramsHash[singleParam[0]] = singleParam[1];
    }
    return paramsHash;
}

This function can then be passed directly to your ajax data field:

$.ajax({
   url: 'url_here',
   data: getUrlParameters(),
   success: function (response) {
        // do stuff
   }
}

Thanks for reading!