lethalMango
lethalMango

Reputation: 4491

jQuery Equivalent for isset($_GET['var'])

I currently have a jQuery function that I need to know if there is any GET data present. I do not need the data from the querystring, just whether there is any or not to run one of two functions.

Equivalent PHP:

if (isset($_GET['datastring'])) {
    // Run this code
} else {
    // Else run this code
}

Upvotes: 6

Views: 8825

Answers (3)

Karl
Karl

Reputation: 595

You would have to try something similar to this: (you don't have to use the variables, but you can if you want)

$.urlParam = function(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results[1] || 0;
}

if ($.urlParam('variable_name') != '') {  // variable_name would be the name of your variable within your url following the ? symbol
    //execute if empty
} else {
    // execute if there is a variable
}

If you would like to use the variables:

// example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id');        // 6
$.urlParam('param2');   // null

Upvotes: 6

Ord
Ord

Reputation: 5843

location.search != ""

Will return true if there are any GET parameters.

From http://www.w3schools.com/jsref/prop_loc_search.asp, location.search returns the "query portion" of the URL, from the '?' symbol onwards. So, for the page http://www.mysite.com/page?query=3, location.search is ?query=3. For http://www.google.com/, location.search is an empty string.

Upvotes: 2

CrayonViolent
CrayonViolent

Reputation: 32532

like this?

if (yourUrlStringVar.indexOf('?')>-1) {
  return true;
} else {
  return false;
}

Upvotes: 1

Related Questions