6

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
}
lethalMango
  • 4,433
  • 13
  • 54
  • 92
  • 3
    Possible dupe: http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript – AndrewR Apr 27 '12 at 17:53
  • You should add that you are using mod_rewrite. In fact, I think that makes this problem unsolvable from the client side. – Ord Apr 27 '12 at 18:22

3 Answers3

6

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
Karl
  • 595
  • 1
  • 10
  • 31
2
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.

Ord
  • 5,693
  • 5
  • 28
  • 42
  • I am using mod_rewrite so unfortunately that doesn't appear to work for this scenario. – lethalMango Apr 27 '12 at 17:59
  • In that case, I am not sure you can get access to the GET parameters. From the client side, all you see is the URL that you asked for. If that is different from the URL that is being used server-side, well, javascript will be oblivious to that. – Ord Apr 27 '12 at 18:04
1

like this?

if (yourUrlStringVar.indexOf('?')>-1) {
  return true;
} else {
  return false;
}
CrayonViolent
  • 32,111
  • 5
  • 56
  • 79