views:

447

answers:

3

How can I get the query string from the browser url using client side js and set it as a variable to use in some server side scripting?

Client side script:

var project = getQueryString("P");

function getQueryString(param) {
    var queryString = window.location.search.substring(1);
    splitQueryString = queryString.split("&");

    for (i=0; i<splitQueryString.length; i++) {
        query = splitQueryString[i].split("=");
        if (query[i] == param) {
        return query[1];
        }
    }

}

Server side script:

response.write ('<td><a href="/index.asp?P=' + project + ">' + obj.BODY[i].NAME + '</a></td>');
+1  A: 

I've used the jQuery plugin getUrlParam to do this in the past. Worked pretty well.

var project = $(document).getUrlParam("P");
Ty W
thanks, but I'm looking for a method that doesn't require using a js library if possible.
George
you could take a look at his plugin's code to see how it is done, then do it yourself without any dependencies on jQuery itself.
Ty W
+1 for this because I have done the same thing in the past without relying on JQuery
Plynx
A: 

You can't set any variable in the client side to be used in a server-side script without passing the value to the server via some HTTP request (possibly XHR). So maybe I am misunderstanding your question.

Server-side scripting is typically used to generate HTML that is sent to the client side, and the server-side script is therefore done executing before the client can do anything, not to mention the server is in a completely different memory space.

Server-side scripting could also receive data from the client side, but only by way of another HTTP request from the client, as mentioned above.

dlaliberte
Perhaps I phrased my question wrong. I know I can't set a variable client side to be used in server-side without passing, my question is how to pass that variable from client side to server (without actually submitting a form or anything that is). I'm outputting several objects server side and would like to link them based on a param in the URL that I can only get client side.
George
A: 

On ASP I think you're looking for String(Request.queryString("P"))

You have to use the String constructor because the queryString method returns a collection.

Nathan L Smith