Saturday, October 30, 2010

How to get patameter from querystring of URL

Query string is frequently used for passing variables or parameters between client (browser) to server (web application) when request a web page. Almost all server side languages have standard function to parse query string to get parameters. But sometimes for some reason you will need to variables and parameters at client side. Java Script is most popular client side language, but does not have stand parser to get parameters or variable from Query String.

Here are code some that will help you get variable or parameter from query string of web page URL.

Java Script code (client side code)

//--------------------------------------------------------
// Get a querystring parameter/variable value from URL
// If no variable specified, return a default value
//--------------------------------------------------------
function get_param_from_querystring(name, defval)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+name+"=([^&#]*)");
var res = regex.exec(window.location.href);
if(res == null) return defval;
else return res[1];
}


Here is PHP code (server side code)

//--------------------------------------------------------
// Get a querystring parameter/variable value from URL
// If no variable specified, return a default value
//--------------------------------------------------------
function get_param_from_querystring($name, $defval)
{
if(isset($_GET[$name]))return $_GET[$name];
else return $defval;
}

No comments: