Get URL query parameter value in Javascript

In this article, I am going to teach you, how you can get the URL query parameter value in Javascript. You can easily get the URL parameter in PHP using PHP’s built-in global $_GET array and pass the associative index as the name of the parameter. But getting that value in Javascript is a bit tricky. So I am going to show you a method that is very simple and will always work.

  1. Create a hidden input field.
  2. Give it a unique ID so it can be accessible in Javascript.
  3. Set its value as the variable you are receiving from the URL using the $_GET array.
  4. Array index will be the name of the parameter as in the URL

Suppose, you are receiving a parameter named “data” in your URL.

<input type="hidden" id="data" value="<?php echo $_GET['data']; ?>" />

Now, create a Javascript tag. You should execute all your Javascript code when the page is fully loaded. So, attach a “load” listener to the window object. You can also use the onload event but it will override the previous event. I have written a detailed post on the difference between onload event and “load” event listener.

window.addEventListener("load", function () {
    var data = document.getElementById("data").value;
    console.log(data);
});

The callback function in the second parameter of the addEventListener function will be called when the page is fully loaded. Now you simply need to get the value of this hidden input field using its ID and get the value attribute. I am logging the value of the data variable in the console.

Now, if you refresh the page then you will see this parameter (data) value in the console using Javascript. That’s how you can get the query parameter from the URL in your Javascript code.

Leave a Reply

Your email address will not be published. Required fields are marked *