Reading URL variables in Javascript
For example you want to get the value of ‘firstname’ on this URL: https://carlofontanos.com/?firstname=carlo&lastname=fontanos
In PHP, we can simply access the value by using the $_GET[], since Javascript does not have any built-in function like this, we need to create our own.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <script type="text/javascript"> jQuery(document).ready(function($){ function cvf_get_url_value(variable) { 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(pair[0] == variable){return pair[1];} } return(false); } }); </script> |
Get the value of ‘firstname’:
1 | cvf_get_url_value('firstname'); |
Do you need help with a project? or have a new project in mind that you need help with?
Contact Me