Prototype - Form serialize() Method


This method is used to 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 on 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.


formElement.serialize([getHash = false]);

Return Value

It returns an String object.

Here are two hints on how it works. For a detail look at the example below.

// 'username = sulien&age = 22&hobbies = coding&hobbies = hiking'
// {username: 'sulien', age: '22', hobbies: ['coding', 'hiking']}


      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
         function showResult() {
            var form = $('example'); 
            var element = form.serialize(); 
            alert("form.serialize() : " + element.inspect());

      <p>Click the button to see the result.</p>
      <br />

      <form id = "example" action = "#" onsubmit = "return false">
            <legend>User info</legend>
               <label for = "username">Username:</label> 
               <input name = "username" id = "username" value = "Sulien" type = "text">
               <label for = "age">Age:</label> 
               <input name = "age" id = "age" value = "23" size = "3" type = "text">
               <label for = "hobbies">Your hobbies are:</label>
               <select name = "hobbies" id = "hobbies" multiple = "multiple">
      <br />
      <input type = "button" value = "Result" onclick = "showResult();"/>