1

How do I know if a $_GET variable has been thrown in my page using jQuery? My $_GET variable is:

?ok=ok

I need to detect if the $_GET['ok'] is set using jQuery but I don't know how.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
marchemike
  • 3,179
  • 13
  • 53
  • 96
  • If you have PHP just check with `isset($_GET['ok'])` instead of trying to get url and use a regex to check if it is set/get value with javascript. – Class Jan 28 '14 at 02:18
  • Do you mean that you want to check whether it's present in the URL? Or whether it's been interpreted by PHP? – TRiG Jan 28 '14 at 02:18
  • @TRiG I want to check if it's present in the url, so I could call a jquery function if it's there. – marchemike Jan 28 '14 at 02:19
  • 2
    So your question has nothing to do with PHP or $_GET. I suggest rewriting and retagging to clarify that. – TRiG Jan 28 '14 at 02:20
  • @TRiG but is it also possible to detect $_GET using Jquery? – marchemike Jan 28 '14 at 02:22
  • Do you understand what $_GET is? It's a language construct in PHP: a superglobal variable. It's an automatically generated representation of the query string. What you're interested in in javascript is *the query string itself*, not whatever your server-side language has done with it. – TRiG Jan 28 '14 at 02:24
  • (Aside: The constant stream of PHP/javascript questions asked by people who have no understanding of the difference between server-side and client-side code is really beginning to bug me.) – TRiG Jan 28 '14 at 02:26

2 Answers2

5

You could just check using PHP if $_GET['ok'] is set, then echo that into a JavaScript variable:

var ok = <?php echo intval(isset($_GET['ok'])) ?>
Anonymous
  • 11,748
  • 6
  • 35
  • 57
2

You can use the following which was taken from How to get the value from URL Parameter?

var QueryString = function () {
  // This function is anonymous, is executed immediately and 
  // the return value is assigned to QueryString!
  var query_string = {};
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
      query_string[pair[0]] = pair[1];
      // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]], pair[1] ];
      query_string[pair[0]] = arr;
        // If third or later entry with this name
    } else {
      query_string[pair[0]].push(pair[1]);
    }
  } 
  return query_string;
} ();

then you can check if $_GET['ok'] is present in url with:

if(query_string.ok !== undefined){
    //$_GET['ok'] is in url
}
Community
  • 1
  • 1
Class
  • 3,149
  • 3
  • 22
  • 31