13 September, 2007

Altering QueryString with Javascript

I'm making a grid in a legacy ASP application. That's right kids, ASP as in Active Server Pages. Old School stuff. None of the ultra-kewl .NET does it all for you stuff. Which, BTW, I really love because I can do so much more so much faster and better. But, alas, the client says "ASP only!" so, I go with ASP.

What they wanted to do was display their data in a grid. Yeah, right, ASP and datagrids, that is a rich one. So what I did was something almost, but not quite, completely different from a grid. I put their data in an HTML table with alternating row colors (hey, at least they think it's in a grid).

But of course, in any good datagrid, one must be able to click on the grid headers and VOILA! the grid sorts by the header clicked. This, I figured out, to do with JavaScript via the QueryString. The table is in an IFRAME, so the URL is never displayed to the end user. Doing this keeps the displayed URL fairly nice and neat. My original though, which seemed to work fairly well was just to cut the QueryString off at the desired parameter, and replace that parameter with the new one as such:

function reSortGrid(str)
{
var idx = location.href.indexOf('&sortby');
var loc = location.href.substring(0, idx);
loc = loc + '&sortby=' + str;
location.href = loc;
}
But then it occurred to me that if any parameters existed beyond the parameter I was replacing, they would be lost. No, what I really needed was to replace the existing sortby parameter within the actual string, while maintaining the rest of the string. This took a little thinking on my part, and what I came up with is:
function resortGrid(str)
{
var newQueryString = '';
if (location.href.indexOf('&sortby') > -1)
{
var locArray = new Array();
locArray = location.href.split('&');
for (i=0; iif (locArray[i].indexOf('sortby') > -1)
{
locArray[i] = "sortby=" + str;
// check to see if this is the start of the QueryString
if (locArray[i].indexOf('?') == -1)
newQueryString = newQueryString + '&' + locArray[i];
else
newQueryString = locArray[i];
}
}else{
newQueryString = location.href + '&sortby=' + str;
}
location.href = newQueryString;
}
So what I ended up with is a QueryString with the correct parameter changed, and the rest of the parameters intact.

3 comments:

1389 said...

Smile! You just made the IT and Computing Links" blogroll at 1389 Blog - Antijihadist Tech!

Unknown said...

I am honored, thanks.

Unknown said...

Here is an example, how to replace querystring value in the url:http://praveenbattula.blogspot.com/2009/04/replace-querystrng-with-some-value-in.html