serialize
serialize(formElement[, getHash = false]) -> String | object
Serialize form data to a string suitable for Ajax requests (default behavior) or, if optional getHash
evaluates to true
, an object hash where keys are form control names and values are data.
Depending of whether or not the optional parameter getHash
evaluates to true
, the result is either an object of the form {name: "johnny", color: "blue"}
or a string of the form "name=johnny&color=blue"
, suitable for parameters in an Ajax request. This method mimics the way browsers serialize forms natively so that form data can be sent without refreshing the page.
As of Prototype 1.5 the preferred form of passing parameters to an Ajax request is with an object hash. This means you should pass true
for the optional argument. The old behavior (serializing to string) is kept for backwards-compatibility.
Interactive example
The following code is all there is to it:
$('person-example').serialize()
// -> 'username=sulien=22=coding=hiking'
$('person-example').serialize(true)
// -> {username: 'sulien', age: '22', hobbies: ['coding', 'hiking']}
Try it for yourself!
Notes
Disabled form elements are not serialized (as per W3C HTML recommendation). Also, file inputs are skipped as they cannot be serialized and sent using only JavaScript.
Keep in mind that "hobbies" multiple select should really be named "hobbies[]" if we're posting to a PHP or Ruby on Rails backend because we want to send an array of values instead of a single one. This has nothing to do with JavaScript - Prototype doesn't do any magic with the names of your controls, leaving these decisions entirely up to you.