Wednesday, July 12, 2006

Get request parameters through JavaScript

This is not original content, I'm just a reciting information I found elsewhere (see original), but with more processing done on the client side in JavaScript for Ajax, it's sometimes necessary to be able to process parameters passed on the URL with JavaScript as you would with PHP, JSP, etc. on the server. So since I found a method to do it, I'm posting it here for my own benefit so I don't have to find it again. You can also download it here.


function getParameter ( queryString, parameterName ) {
// Add "=" to the parameter name (i.e. parameterName=value)
var parameterName = parameterName + "=";
if ( queryString.length > 0 ) {
// Find the beginning of the string
begin = queryString.indexOf ( parameterName );
// If the parameter name is not found, skip it, otherwise return the value
if ( begin != -1 ) {
// Add the length (integer) to the beginning
begin += parameterName.length;
// Multiple parameters are separated by the "&" sign
end = queryString.indexOf ( "&" , begin );
if ( end == -1 ) {
end = queryString.length
}
// Return the string
return unescape ( queryString.substring ( begin, end ) );
}
// Return "null" if no parameter has been found
return "null";
}
}


The queryString is obtained via var queryString = window.top.location.search.substring(1);

2 comments:

Anonymous said...

Thanks that's great!
Tom.

Anonymous said...

Another useful thing to be able to do when using AJAX is send POST parameters to an AJAX server script. I've found this can be done by using www.gettopost.com to convert the GET request in a URL into a POST request.