views:

77

answers:

2

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!

+4  A: 

This page has a good run down. You don't need jQuery to do it. Their jQuery version is:

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

Use it with:

// Get object of URL parameters
var allVars = $.getUrlVars();

// Getting URL var by its nam
var byName = $.getUrlVar('name');
Blair McMillan
+4  A: 
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

Fosco
I was just about to post this, too! [(Source)](http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx)
jnpcl