phpjavascriptjqueryformsget-method

Is there a JQuery or JS equivalent to PHP's $name = $_GET['name']


I'm trying to figure out a way to read GET method information from a form with javascript. Our IT department has our servers on lockdown, and as the web team we can only use javascript to accomplish our tasks. I'd use PHP if I could, but I can't.

What I need to do is read data sent via GET method in js if possible, so that I can assign the data into variables, and use it on individual pages after a user takes action on a form.

ie. if data is sent in the url http://somesite.com?add_to_cart=true&items=10

Any help would be appreciated!


Solution

  • function getQuerystring(key, default_)
    {
      if (default_==null) default_=""; 
      key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
      var qs = regex.exec(window.location.href);
      if(qs == null)
        return default_;
      else
        return qs[1];
    }
    
    var addtocart = getQuerystring('add_to_cart','false');
    

    source: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx