1
www.mywebsite.com/?foo=bar

How can I get the value of foo into a Javascript variable?

0

4 Answers 4

5

You don't even need PHP for that. Basically, you can parse window.location.href to get the value of a GET URL parameter into a JavaScript variable.

There is plenty of code online, you can use for example this:

function getUrlParameter( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

To get the value of foo, just call getUrlParameter("foo") in your JavaScript code.

Sign up to request clarification or add additional context in comments.

2 Comments

gup? really? Come on. Descriptive function names!
Changed, although the code is taken from the link, so the name wasn't mine :)
1

You can parse the window.location.search string for query variables.

https://developer.mozilla.org/en/DOM/window.location

For example

var query = window.location.search.substring(1);
var pairs = query.split('&');
var _get = {};
for (var i = 0; i < pairs.length; i++) {
    var pair = pairs[i].split('=');
    _get[pair[0]] = pair[1];
}

Comments

1

I did some googling and here is a link for you http://www.zrinity.com/developers/code_samples/code.cfm/CodeID/59/JavaScript/Get_Query_String_variables_in_JavaScript

Comments

1

You can try this

 function getUrlVars()
{
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;
}

EDIT

The above will parse the URL and give you the parameters as an associative array. You can also try

function getURLVars(name) {
return decodeURI(
    (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
 );
}

In this if you want the value of foo, call this with getUrlVars('foo')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.