javascriptjqueryquery-stringdocument-readyurl-parameters

How to access variable passed in a query string into document.ready function of jQuery?


I'm loading a page with URL as follows :

http://localhost/CKWEB_28-12-2015/event_index.php?event_id=510

I tried following code to access the value of a variable event_id as follows :

$(document).ready(function() {

  var query_event_id = $.url().param('event_id');
  alert(query_event_id);
});

But no success. Can somebody please help me in accessing the value passed in a query string?

Thanks.


Solution

  • You need a function to get the appropriate info from the query string.

    There is a good one in this thread: How can I get query string values in JavaScript?

    Applying that to your situation you can do the following:

    function getParameterByName(name) {
      name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
      var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
          results = regex.exec(location.search);
      return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    
    var query_event_id = getParameterByName('event_id');
    if(query_event_id){
      alert(query_event_id);
    }
    

    By checking if the query_event_id value evaluates to something truthy, you avoid taking any action if the query string is not present.

    Also, if you include your JavaScript at the bottom of the page, before the closing </body> tag, you can avoid the call to $(document).ready(...);