URL Parameters are something that you see in the URLs a lot these days. They look like “http://www.example.com/?category=xyz”, where “category” is the parameter name and “xyz” is the parameter value. These typically appear in the URL of a page when we submit a form on the previous page, and it sends the data to the action page via a GET method.
However, it is totally possible to pass on these parameter values manually by providing the linking URL as the one with the parameters already in them. Now, the question arises what can we do with these parameters, or how do they benefit any developer. But before we get into the technicalities of that, you might want to read a few other jQuery tutorials that I have previously shared.
- Create a stylish jQuery tooltip using a plugin
- Create a sticky menu bar using jQuery
- Create a full page loading animation using jQuery
Reasons to Use URL Parameters in your URLs
There are various reasons to use URL Parameters in your URLs. If you are coding in PHP, you might have used $_GET array quite a few times. It gets the values that were set to it in a similar way that I described above. But now coming over to jQuery, what are the things we can do with these?
- Use the Parameter value to sort some data using jQuery
- Use the parameter value to perform certain actions, like scrolling down with effects to a certain point on the page
- Use the parameter value to dynamically display content to the user
The things that you can do with these URL parameters are more or less the same that you could do with them in PHP, but the good thing is that it doesn’t require any back-end coding in PHP to perform actions.
How to read URL Parameters and perform action based on their values
The procedure to read the parameters is pretty simple using jQuery. Here is a simple code snippet that would help you read these parameters for your web page. Be sure to include the latest version of jQuery before this code.
In the above code, we basically call the function decodeURL() when the page loads completely. The function then reads the URL of the current page and sees if there are any parameters specified in the URL, it will generate an alert stating the value of the parameter ‘category’. Instead of generating this alert box, you can perform whatever action you want.
I hope this tutorial helped you learn a new thing that you can implement in your future projects, or even incorporate them in your existing projects. If you face any problem following this tutorial, do leave a comment down below to let me know what the problem is and I’ll surely help you out with the solution to that. Don’t forget to subscribe to the Slash Coding email newsletter so you don’t miss out on any article written on this blog. Also, follow us on Facebook and Twitter to stay updated with our upcoming articles and tutorials.