Processing Forms with JavaScript

Occasionally you can’t use server-side languages to deal with form input. In my case it’s because my university coursework assignment had to be done in JavaScript, but who knows what your reasons could be.

This snippet of code has a few good points:

  • It’ll take standard forms with no javascript and parse the inputs.
  • You can use the GET method to send the data.
  • It’s simple, short and cross-browser compatible.

And some bad..

  • You can’t handle submitted files (not really tested it though)
  • You can’t do things with POST’ed forms.
  • You really shouldn’t be processing anything important on the client-side, as it’s open to a multitude of attacks.

But anyway, I shall walk you through my thinking…

To start with, lets all remember what a sample GET request might look like..
[code]http://www.jak.cx/folder/file.html?cheese=cheddar&type=mature[/code]

[js]
function getUrlValues() {
    keyvalue = new Array();
    var url = new String(window.location);
    if (url.indexOf("?") < 1)
        return (new Array());

[/js]

It’s just one function which returns an array for anyone to use, simple enough. After creating an array to store everything in before returning it, I’ve had to take the URL of the page and turn it into a String because GET submissions are appended to the URL (e.g. mypage.html?something=here ). It’s necessary to parse it into a String object because window.location is a different object with many properties and simply doesn’t behave like a String.

I’ve also placed a quick check to see if anything at all was actually appended to the URL. url.indexOf(“?”) will return 0 if the question mark doesn’t exist.

[js] 

    var param_string = url.split("?")[1];
    var params = (param_string.indexOf("&"))?param_string.split("&"):param_string;

[/js]

Here I’m extracting everything after the question mark on the first line. The split method is handy and creates an array from literally splitting the string up wherever the character or string occurs. The [1] after it is fetching the second part.

Our URL information now looks like this:
[code]
cheese=cheddar&type=mature
[/code]

Now I’m repeating the idea but with the ampersand (&) to split the combined fields sent. This inline if statement will return the array if there are many, or the original string if no ampersand exists.

Our URL information now looks like this:
[code]
cheese=cheddar
type=mature
[/code]

[js] 

    var key, value;
    for (x in params) {
        if (params[x].indexOf("=") > 0) {
            kv = params[x].split("=");
            key = kv[0]; value = kv[1];
        } else {
            key = params[x];
            value = true;
        }
        keyvalue[key] = value;

[/js]

This looks like a lot, but a does a simple task of yet again splitting the strings we have where the equals sign is noting both the first “key” part (i.e cheese) and the value assigned to that key (i.e. cheddar). If it finds there is a key without a value, it’ll assign a default value of true ( lines 7-10 ). The final part is loading this into an associative array ready to be returned.

Here’s the full code..

[js]
function getUrlValues() {
    keyvalue = new Array();
    var url = new String(window.location);
    if (url.indexOf("?") < 1)
        return (new Array());
    var param_string = url.split("?")[1];
    var params = (param_string.indexOf("&"))?param_string.split("&"):param_string;
    var key, value;
    for (x in params) {
        if (params[x].indexOf("=") > 0) {
            kv = params[x].split("=");
            key = kv[0]; value = kv[1];
        } else {
            key = params[x];
            value = true;
        }
        keyvalue[key] = value;
    }
    return keyvalue;
}
[/js]

Sample usage:
[js]
var args = getUrlValue();
if (args[‘cheese’] == "cheddar") {
  alert("Nice and tasty choice. I see you like it "+args[‘type’] );
} else {
  alert("What kind of cheese is "+args[‘cheese’]+"?");
}
[/js]