Request.QueryString() for Javascript (ver. 1.41)
Overview
This web page is the home of
the “CSJSRequestObject”
script. The CSJSRequestObject is a free client-side javascript function that mimics
ASP's server-side Request.QueryString()
command. It is designed for use in ordinary HTML
pages. It allows you to easily read data in URLs
after the “?”. E.g. If the script has been added to the HTML source of
“somepage.html” on the “www.example.com” webserver,
then with a URL like “http://www.example.com/somepage.html?username=bill”
you can use this script to test if “username” exists in the URL and retrieve
its value (“bill”) for use in your own scripts.
Full details follow of what the script can do and how you can use it, including some live interactive
working examples. This script is the only one that I know of that attempts to mirror the exact behaviour
of the equivalent ASP version — so if you're
familiar with the Request.QueryString() command in ASP then you should find it very easy
to use this script.
Who Is The Script For?
The script and this documentation are aimed at web site authors that have at least a basic understanding of javascript (a common client-side scripting language). The script is most suitable for use with personal and hobby web sites, but it is not aimed at professional developers (they should be using server-side technologies instead).
Accessibility note:: This script should not be used in situations where information cannot be accessed unless javascript is available/enabled in a user's web browser - e.g. don't use it as the sole means of page navigation. Users that access web pages in less obvious ways, such as via screen-readers, Braille producers, simple mobile devices or even users behind certain corporate firewalls, may not have javascript support and so relying on this script (or any other script) could deny those users access to your site if you're not careful. If you use the script such that content is inaccessible to non-javascript users you could breach accessibility discrimination laws in the country where the web page and script are being viewed or served. This issue is obviously not limited to this particular script but to all client-side scripting. To overcome accessibility issues use a server-side HTML processing language instead — hence the caveat above for professional developers.
Download It
To use the script you'll need to download it from this site and upload it to your web site. The size of the current version of the script is 5.29KB and has the file name “CSJSRequestObject.js”. You will most likely need to right-click and choose “Save Target As...” or equivalent to save it to this computer and then use an FTP program to upload it to your own site. You only need a single copy on your web site and it does not need to reside in the same directory/folder as the web page that is using it.
Note: Please upload the script to your own site (as described above)
— don't write your web pages such that they download the the script directly from my website
(e.g. don't write a script “src” value of “http://andrewu.co.uk/tools/request/download/”)
— that's not nice and will just lead to me blocking access to the script from your site.
This version of the script has been ‘reduced’ to make it download faster for your own visitors. However, if you would like a copy that can be read and edited then you can download the expanded version [7.94KB].
Forum
I occasionally receive requests for help with folk's code but I usually don't have the time (or patience!) to properly answer them. To help remedy this situation I've created a basic forum where you can browse or search for questions and read the answers that may have been given. You are also free to ask new questions and to add your own answers to existing questions. Hopefully this will help you find the help you're looking for faster than if you ask me directly.
Examples
I've written a number of live example pages for you to have a look at the script in action. The HTML in these example pages contains comments to help you understand what is happening in each example. If like me you prefer to learn hands-on rather than reading a manual you might like to start your education with the examples and then come back to this page later on. Links to the examples follow:
- Example 1 - As Simple As It Gets
- Example 2 - Using A Mixture Of Form Input Elements
- Example 3 - Displaying Alternatives For Empty Form Inputs
- Example 4 - Coping With HTML In Form Inputs
- Example 5 - Using The Script Without Forms, Plus Accessibility Issues.
Additionally, advanced users that are familiar with the original ASP command may want to try a like-for-like comparison of my script against ASP. Advanced users may also wish to browse the complete list of ways to use the script in the advanced manual, but it's not for the feint of heart :-)
How do I use it in my pages?
Simply download the script and upload it to your web server as described above.
Then write the following HTML into any page that you wish to use the script with. It is preferable
to place the script between the <head> </head> tags. For example:
<title>My First Example</title>
<script type="text/javascript" src="CSJSRequestObject.js"></script>
</head>
The file name in the “src” attribute should point to the exact location
on your web server where you have uploaded the script to. You can then use the “Request.QueryString”
command in any subsequent javascript that follows that script tag:
var name = Request.QueryString("username");
alert("Hello " + name + "!");
</script>
In the example above the address of the page containing this script might have
looked like “http://www.example.com/somepage.html?username=bill”. If that was
the case then the variable we created called “name” would now contain
the string “bill”.
A querystring is said to contain “key-value pairs”. In the above example “username”
is the “key” and “bill” is the value. A querystring may contain
many “key”s with the same name, there's more on this in the advanced manual.
Troubleshooting
Note that “Request.QueryString” is case-sensitive,
so writing “request.querystring” will not work.
The “Request.QueryString” command always returns a String or the “null” Object.
To convert a result returned by the “Request.QueryString” command into a number
use the appropriate javascript conversion function for the type of number you are expecting. I.e. use
parseInt(string, 10) for integers, parseFloat(string) for decimals
or Number(string) for either format.
If you see an error such as “Request is undefined” then the web browser didn't download
the script properly. This is almost always because the “src” attribute of the
script tag isn't pointing to the correct location for the script on your webserver. Please don't report
these ‘errors’ as bugs, they aren't — you just need to experiment to find the right value
for the “src” attribute for your webpage and webserver.
Alternatively the script may have been corrupted when you downloaded it from this site
and uploaded it to your own site, these things do happen albeit rarely.
The script has been exhaustively tested on a range of web browsers and operating systems. I have a list of browsers and systems that have been tested to date and a list of known problems.
A Note About Frames
This script uses the address location of the current “self” window. In normal
non-frame circumstances this is the desired behaviour. However, in a frames environment this leads to a
decision as to which page should contain the initial script tags. For example should it be placed in the
frameset page or should it be placed inside one of the framed pages? Since the script is designed to read the
URL of the page it is placed in, the answer is put the script in the specific page who's URL
you want to use. So if you always want to read the web-browser address-bar location (the “top” location)
then this script must be placed in the frameset definition page for a frames enabled site.
Otherwise place the script within one of the framed pages to read the URL of that individual framed
page. In this latter situation the URL of the page will not be visible in the web-browser's address-bar.
Creating a QueryString
To create a web page address with a querystring on it you normally need a form where the
“method” attribute of the HTML “<form>” tag has been set to
“get”. For example:
<fieldset>
<legend>Example Usage</legend>
<input type="text" name="username" value="Bill">
<input type="submit" value="Submit">
</fieldset>
</form>
When the above example form is submitted to “example.html” the web page address will look like
example.html?username=Bill. Our example.html page may then retrieve the value of the
input box called “username” using the example I described in How do I use it in my pages?.
However, a more programmatically correct (and safer) way of retrieving the data is:
/* If the 'key' called 'username' exists in the querystring,
then read out the first occurrence of it only. Otherwise
assign a default alternative value instead. */
var name = "Anonymous"; // Default value
if (Request.QueryString("username").Count > 0) {
name = Request.QueryString("username").Item(1);
}
</script>
Why is this more programmatically correct? There are two reasons. The first reason is
that you only want to retrieve the value for “username” if
the key with that name actually exists in the URL. The second reason has to do with
something I mentioned earlier about having more than one key with the same name in a
URL. At that time I said to have a look in the advanced manual
if you wanted to know more about this, but now I'll briefly introduce the idea of multiple
keys.
If our URL looked like “example.html?username=bill&username=FishFace”
then a simple “Request.QueryString("username")” statement
would return to us both values of the key named “username” separated by a comma. But for
the sake of our example we only want the first occurance of “username”
in the URL, any extras ones we just want to ignore (this is nearly always the case in practice).
So, to just pick the first instance we can use the “Item()” method
to specify the number of the occurance we want to use. In other words
“Request.QueryString("username").Item(1)” will just return
to us the value “bill”. So, our more pedantic code has checked to see if the key
name we are looking to use actually exists, and if it does we only pick the first occurance
of that key name in the URL. If the key name doesn't exist (the Count was zero)
then we follow the else branch and compensate for the missing data.
For an exhaustive list of commands and how to use them, see the advanced manual.
What does it cost?
The script is free to any user or entity who wishes to use it be they commercial, governmental or anyone else. Note though that it is only free if the copyright notice below remains attached to the script.
Copyright
The following text is included with the script. It must remain with the script and may not be edited or deleted - unfortunately doing so forfeits your right to use this script for free. This should only be a small inconvenience though.
COPYRIGHT:You are free to use this script for any use you wish if this comment is left intact. Feel free to enhance the script and send me the updated version. Please don't redistribute. This script is provided as is,with no warranty of any kind. Use it at your own risk. Copyright Andrew Urquhart; VERSION:#1.41 2007-06-28 18:10 UTC*/
Browser Compatibility
This script has been tested successfully in the following browsers:
- Windows
- Internet Explorer 5.0 and above
- Mozilla 0.9.7 (at least) and above
- Netscape Navigator/Communicator 4.08 and above (including versions 6 and 7)
- Opera 5.12 and above
- Safari for Windows 3.0.1
- Mac
- Internet Explorer 4.01, 4.5, 5.0 (PowerPC)
It has been tested unsuccessfully in these browsers:
- Windows
- Netscape Navigator 3.04
Please note that browsers and versions not listed above simply haven't been tested.
I expect it to work in any browser supporting Javascript version 1.2 and equivalent implementations so it should work fine with Windows IE4. However, Windows IE4 and other browsers have not been tested with it, and I would greatly appreciate it if you could send me a quick note to tell me if it worked in this or some other browser not listed above. You can do this anonymously at the feedback page.
Version Information
There have been several version of the “CSJSRequestObject” script. A history follows:
- 1.4 CURRENT
- Implemented decoding of querystring values using
decodeURIComponent()if the user's web browser supports it, else resorts to usingunescape. This ensures better Unicode compliance, e.g. decoding Hebrew - 1.3
- Changed the behaviour of the script so that it returns the keyword “
null” instead of the String “undefined” when de-referencing non-existant querystring keys. Prior to version 0.65 the script used to return the keyword “undefined” rather than the String “undefined”, but problems with lack of support for that keyword on the Mac platform forced me to change the behaviour. This consequently made it awkward when implicitly casting to Boolean types since the String “undefined” would yield Boolean true when you really wanted the answer Boolean false. Consequently I've change the script to use “null” which will cast to Boolean false. The original behaviour of returning the string can be re-instated by changing the source so that the value of “x” is “"undefined"” and not “null”. Alternatively if you will only be using the script in a controlled environment and you know that all client browsers will support the “undefined” keyword then you could set “x” to “undefined” for maximum classic ASP simulation — but I wouldn't recommend it. - 1.2
- Reduced the size of the script to 5.27KB using a script compressor I wrote
- 1.1
- Reduced the size of the script to 5.68KB
- 1.0
- Since no bug reports have been received in months and months, have decided to go to version 1.0. Script also reduced slightly to 6.48KB
- 0.68 (Beta)
- Set the error alerts to off by default and reduced the script to 6.54KB
- 0.67 (Beta)
- Script reduced further to 6.74KB
- 0.65 (Beta)
- Fixed issue with the use of
undefined, but as a consequence have introduced a bug (2002-01-04). Also fixed bug introduced with last update to do with empty querystringexample.html? - 0.6 (Beta)
- A re-write using a more object-based structure. This allows for enumeration using the "
in" statement, see Issues for further information. A number of subtle and not-so-subtle bugs have been discovered in version 4 and have been fixed in this version - I hope. Performance may improve and less memory should be consumed. In addition commands such as “Request.QueryString("user")[1]” andRequest.QueryString(X);have been introduced. - 0.4 (Beta)
- Fixed a case sensitivity issue.
- 0.31 (Beta)
- Now easier to turn off alert-based error messages.
- 0.3 (Beta)
- Fixed bug with certain special characters in URL.
- 0.2 (Beta)
- First beta release.
Security Issues
Users are reminded of the following security
advisory regarding cross-site scripting. Fortunately there is a solution, and for client-side
scripts like this one the problem isn't a serious one anyway, bordering on not being an issue at all.
An example of the issue described in the advisory is illustrated by the following
example URL
where we “document.write” a value directly from the URL when the URL actually
contains some HTML tags — those tags are interpreted by the web browser as HTML rather than being
displayed as plain text and in the example the tags were script tags and contained an “alert”
statement. However, this is really only a problem if at some point a web server is being used to store
querystring information that other users might see. The conclusion is then that web site authors only
using this script (or any other like it) in a client-side environment with no server-side capability
are unlikely to have a problem with this advisory.
However, just in case, a means to prevent URL values like those in the above example from writing
HTML or executing javascript during “document.write” commands
is to replace the “<” and “>” with “<” and
“>”. This will disable any HTML. To replace HTML tags you could use
the following verbose function to do this replacement for you — as shown in the example at the end:
var html = "" + strHTML;
var arrE = [["&","&"], ["\"","""] ,["<","<"], [">",">"]];
var arrO = [];
for (var i=0, j=html.length, k=arrE.length; i<j; ++i) {
var c = arrO[i] = html.charAt(i);
for (var l=0; l<k; ++l) {
if (c == arrE[l][0]) {
arrO[i] = arrE[l][1];
break;
}
}
}
return arrO.join("");
}
var firstname = Request.QueryString("firstname");
document.write("Hello " + getHTMLEncode(firstname));
Alternatively if you only need to support browsers that support Regular Expressions (which these days is more or less all of them bar Netscape 4) you could use this much more succinct version:
return t.toString().replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">");
}
var firstname = Request.QueryString("firstname");
document.write("Hello " + getHTMLEncode(firstname));
Example 4 describes how this is done.
Known Bugs
There are no known critical or major bugs, only the following minor issues:
- (2007-03-25) Old browsers such as Internet Explorer 5.0 and below won't properly handle certain international character sets, e.g. Hebrew. More recent browsers, specifically browsers supporting Javascript 1.5, should be unaffected by this problem.
- (2002-01-04) You may not use a key named “undefined” although values of “undefined” are OK. E.g.
example.html?undefined=5will give incorrect results butexample.html?5=undefinedis OK. This has arisen because of a work-around for the absence of theundefinedkeyword in some browsers with the introduction of version 0.65 Beta. - (2001-12-24) When indexing keys by number e.g.
Request.QueryString(1)no assumptions can be made as to which key name this index number corresponds to. See Issues for further information. - (2001-12-24) “
Request.QueryString("user")(1)” syntax is supported as “Request.QueryString("user")[1]” - using square brackets.
Advertisement
Feedback
You may also add feedback about the documentation.