Form and HTTP Utilities

While certain AJAX designs can certainly be breathtaking if implemented properly, let's not forget that certain tried and true elements like plain old HTML forms are far from obsolete and still have prominent roles to play in many modern designs—with or without AJAXification. Three functions that Base provides to transform forms include:

dojo.formToObject(/*DOMNode||String*/ formNode) //Returns Object
dojo.formToQuery(/*DOMNode||String*/ formNode) //Returns String
dojo.formToJson(/*DOMNode||String*/ formNode) //Returns String

To illustrate the effect of each of these functions, let's suppose we have the following form:

<form id="register">

    <input type="text" name="first" value="Foo">
    <input type="button" name="middle" value="Baz" disabled>
    <input type="text" name="last" value="Bar">

    <select type="select" multiple name="favorites" size="5">
        <option value="red">red</option>
        <option value="green" selected>green</option>
        <option value="blue" selected>blue</option>
    </select>

</form>

Here's the effect of running each function. Note that the disabled form element was skipped in the transform.

formToObject produces:

{
    first: "Foo",
    last : "Bar",
    favorites: [
        "green",
        "blue"
    ]
};

formToQuery produces:

"first=Foo&last=Bar&favorites=green&favorites=blue"

formToJson produces:

'{"first": "Foo", "last": "Bar", "favorites": ["green", "blue"]}'

Base provides the following additional convenience functions to you for converting a query string to an object and vice versa. They're just as straightforward as you might imagine with the caveat that the values in query string are converted to strings, even when they are numeric values :

dojo.queryToObject(/*String*/ str) //Returns Object
dojo.objectToQuery(/*Object*/ map) // Returns String

Here's a quick snippet to illustrate:

//produces {foo : "1", bar : "2", baz : "3"}
var o = dojo.queryToObject("foo=1&bar=2&baz=3");

//converts back to foo=1&bar=2&baz=3
dojo.objectToQuery(o);

Get Dojo: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.