Hi all.

I have the following form:

<form id="registrationForm">
            <input id="forename" type="text"></input>
            <input id="surname" type="text"></input>
            <input id="emailAddress" type="text"></input>
            <input id="password" type="password"></input>
            <input id="confirmPassword" type="password"></input>
            <input id="agreeToTerms" type="checkbox"></input>
            <input id="clickToRegister" type="button" 
                onClick="javascript:SpeakAtServer(FormToJson('registrationForm'))"
                    value="Register"></input>
</form>

...with the following JavaScript...

FormToJson = function(sourceElement) {
    var JsonToServer = new Object();
    if (document.getElementById(sourceElement).childNodes) {
        var form = document.getElementById(sourceElement);
        var data = new Object();
        for (var element = 0; element < form.length; element++) {
             // Get the id e.g. firstname, surname, emailAddress etc...
            var key = form.elements[element].getAttribute("id");
            // Get the value e.g. Jane, Doe, jane@example.com etc...
            var value = form.elements[element].value;
            // Build a key/value pair e.g. "firstname":"Jane" etc...
            data.key = value;
        }
        JsonToServer.formData = data;
    }
    return JSON.stringify(JsonToServer);
}
SpeakAtServer() {
    // Generic Ajax function that sends the JSON to a PHP script which then
    // returns a copy of what it received e.g. {"JsonData":"SomeData"}
}

I was hoping that I would get something like:

{"formData":{"forename":"Jane","surname":"Bloggs" etc...etc...}}

...but instead I got:

{"formData":{"key":"Register"}}

...which suggests my JavaScript is partially working, but is failing on my attempt to make Key/Value pairs. Unfortunately, I'm not knowledgeable enough on JavaScript/DOM to identify an error and would be grateful if a more seasoned programmer could let me know the error of my ways.

Thanks in advance for any help/tips/pointers. :)

JRW,

You can build a JSON string like that if you want ( data[key] = value; will get you started) but unless you particularly need a JSON string, you appear to be trying to replicate something that's native to HTML/browsers (and has been since time immemorial - ie Mosaic, IIRC).

HTML forms are designed for submission to a server when a "submit" button is clicked. You control the submission behaviour with form attributes (see eg. here).

The user's data/settings are submitted against the form elements' name attributes, rather than their id .

If necessary (for other reasons), you can set form elements' name and id to the same string, eg.

<input id="forename" name="forename" type="text" />

Airshow

What is form.length?? Does this line make any sense??

form.length is the same as form.elements.length , ie, the number of form elements of all types.

I think both work cross-browser but I haven't checked.

The function would be written more conventionally as follows:

var FormToJson = function(formId) {
    var i, data = {}, el;
    var form = document.getElementById(formId);
    if (form && form.length) {
        for (i=0; i<form.length; i++) {
            el = form.elements[i];
            data[el.id] = el.value;
        }
    }
    return JSON.stringify(data);
}

The more suspect line is actually data[el.id] = el.value; , which is not universal as it only handles elements with a value while others require a different treatment (eg. checkboxes are either checked or !checked ).

Airshow

Thanks Airshow!

JRW,

You can build a JSON string like that if you want ( data[key] = value; will get you started)

Thanks!!! I re-wrote the code to:

FormToJson = function(sourceElementId, targetElementId) {
    var JsonToServer = new Object();
    JsonToServer.targetElementId = targetElementId;
    JsonToServer.formData = new Object();
    var form = document.getElementById(sourceElementId);
    for (var element = 0; element < (form.length - 1); element++) {
        JsonToServer.formData[form.elements[element].getAttribute("id")] = form.elements[element].value;
    }
    return JsonToServer;
}

...and it now works flawlessly on Firefox 3.5 (haven't tried on IE or others).

but unless you particularly need a JSON string, you appear to be trying to replicate something that's native to HTML/browsers (and has been since time immemorial - ie Mosaic, IIRC).

The JSON is required by the PHP script I have written. I want to give my website the look and feel of an application and found that sending JSON via Ajax helps me achieve it.

OK, JSON via AJAX makes sense.

Airshow

I agree with you Airshow. Thanks!

javascript Syntax (Toggle Plain Text)

1.
FormToJson = function(sourceElementId, targetElementId) {
2.
var JsonToServer = new Object();
3.
JsonToServer.targetElementId = targetElementId;
4.
JsonToServer.formData = new Object();
5.
var form = document.getElementById(sourceElementId);
6.
for (var element = 0; element < (form.length - 1); element++) {
7.
JsonToServer.formData[form.elements[element].getAttribute("id")] = form.elements[element].value;
8.
}
9.
return JsonToServer;
10.
}

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.