Chapter 11. Form Plug-In

You better find out

Before you fill in the blanks

—Devo,

"Find Out"

The Form plug-in is a terrific example of a script that makes a difficult, complex task dead simple. It assists us in AJAX submission of forms (even if the forms contain file upload fields), as well as inspection and manipulation of the contents of form fields.

These methods assist in submitting a form's contents to the server using AJAX calls.

Sends a form's contents to the server without a page refresh.

.ajaxSubmit(success)
.ajaxSubmit(options)

The .ajaxSubmit method issues an AJAX request using the provided url and type information, along with the data currently present in the form. The form contents are encoded using the .formToArray method, and intricacies such as file uploading are handled behind the scenes.

If a callback is provided using the beforeSubmit option, the callback will be fired before the request is sent. This gives us an opportunity to perform last-minute validation or cleanup. If a validation routine detects errors that the user must correct, the routine can return false to prevent the form from being submitted. The callback is passed the form data as returned by .formToArray(), the jQuery object that references the form, and the options object that was provided to .ajaxSubmit(). For an example of this callback in action, see the example in the discussion of .ajaxForm() later.

When a dataType is provided, the response data is interpreted accordingly. The processing performed is the same as with the $.ajax function for the supported data types. Any script responses are interpreted as JavaScript and executed in the global context, while json responses are parsed as a JavaScript object or array. Calls that specify an xml data type do not cause any parsing to occur when the response is received.

If no dataType is provided, then we can instead use the target option. The DOM element referred to by the target will be filled with the response to the AJAX request, interpreted as plain HTML. The dataType and target options are mutually exclusive.

After any relevant processing has been performed due to the dataType or target options, the success callback is executed. This function is given the response data to act on. For information on ways to interpret and manipulate the response data, see the $.ajax function discussion in Chapter 7.

The semantic flag forces strict semantic ordering at the expense of execution speed. For more information, see the .formToArray() discussion later.

If resetForm or clearForm is set to true, the corresponding action will be taken before the success callback (if provided) is executed. For more information on these actions, see the .clearForm and .resetForm method discussions later.

If the form that is being submitted contains file upload fields, the file data will be properly uploaded using the multipart/form-data MIME type. No further action needs to be taken.

Note that the .ajaxSubmit method executes immediately. Since it is common to issue the AJAX request when the submit button is clicked, it is typically more convenient to use the .ajaxForm method instead. However, the direct action of .ajaxSubmit() may be the easiest way to achieve interaction between this plug-in and others, such as the popular Validation plug-in.

Prepares a form for automatic AJAX submission.

.ajaxForm(options)

The .ajaxForm method prepares a form for later submission by AJAX. When the form is submitted, the AJAX request will use the provided url and type information, along with the data currently present in the form. The form contents are encoded using the .formToArray method, and intricacies such as file uploading are handled behind the scenes.

Unlike the .ajaxSubmit method, the .ajaxForm method does not cause immediate action. Instead, it binds handlers to the submit event of the form and the click events of form buttons, which in turn cause the form contents to be sent as an AJAX request. This removes some of the work in setting up an AJAX form.

In addition, the .ajaxForm method is able to simulate other aspects of a standard form submission that the .ajaxSubmit method cannot. The name and value of the submit button that was clicked are included with the request when .ajaxForm() does the job. Also, when a form contains an <input> field of type image, .ajaxForm() can capture the mouse coordinates and send them along with the request.

For best results, the Dimensions plug-in should also be present when using image inputs. The Form plug-in will auto-detect the presence of Dimensions and use it if possible.

The .ajaxForm method can be used with forms containing any standard field type:

<form id="test-form" name="test-form" action="submit.php" method="post">
  <div class="form-row">
    <label for="city">City</label>
    <input type="text" id="city" name="city" size="20" />
  </div>
  <div class="form-row">
    <label for="state">State</label>
    <input type="text" id="state" name="state" size="5" value="MI" />
  </div>
  <div class="form-row">
    <label for="comment">Comments</label>
    <textarea id="comment" name="comment" rows="8" cols="30">
    </textarea>
  </div>

  <div class="form-row">
    <label for="sacks">Villages sacked</label>
    <select name="villages" id="villages">
      <option value="0">none</option>
      <option value="5" selected="selected">1-5</option>
      <option value="10">6-10</option>
      <option value="20">11-20</option>
      <option value="50">21-50</option>
      <option value="100">51-100</option>
      <option value="more">over 100</option>
    </select>
  </div>
  <div class="form-row multi">
    <span class="multi-label">Preferred tactic</span>
    <input type="radio" name="tactic" value="loot" id="loot" checked="checked" /><label for="loot">loot</label>
    <input type="radio" name="tactic" value="pillage" id="pillage" /><label for="pillage">pillage</label>
    <input type="radio" name="tactic" value="burn" id="burn" /><label for="burn">burn</label>
  </div>

  <div class="form-row multi">
    <span class="multi-label">Viking gear</span>
    <input type="checkbox" name="gear[helmet]" value="yes" id="helmet" checked="checked" /><label for="helmet">horned helmet</label>
    <input type="checkbox" name="gear[longboat]" value="yes" id="longboat" /><label for="pillage">longboat</label>
    <input type="checkbox" name="gear[goat]" value="yes" id="goat" checked="checked"/><label for="goat">magic goat</label>
  </div>

  <div class="form-row buttons">
    <input type="submit" id="submit" name="submit" value="Send" />
    <input type="button" id="more" name="more" value="More Options" />
  </div>
</form>

To prepare the form for submission, we only need to call .ajaxForm() once, when the DOM is ready:

The user can then fill in the form fields:

Discussion.ajaxForm()about

When the Send button is later clicked, the server receives all of the form information without a browser refresh. For testing purposes, we can use PHP's print_r function to display the posted form contents:

If a callback is provided using the beforeSubmit option, the callback will be fired before the request is sent. The callback is passed the form data as returned by .formToArray(), the jQuery object that references the form, and the options object that was provided to .ajaxForm(). This callback is primarily useful for performing form validation:

If a validation routine detects errors that the user must correct, the routine can return false to prevent the form from being submitted. In our example here, a value must be entered in the City field, or an alert will be shown and no submission will occur.

When a dataType is provided, the response data is interpreted accordingly. The processing performed is the same as with the $.ajax function, for the supported data types. Any script responses are interpreted as JavaScript and executed in the global context, while json responses are parsed as a JavaScript object or array. Calls that specify an xml data type do not cause any parsing to occur when the response is received.

If no dataType is provided, then we can instead use the target option. The DOM element referred to by the target will be filled with the response to the AJAX request, interpreted as plain HTML. The dataType and target options are mutually exclusive.

After any relevant processing has been performed due to the dataType or target options, the success callback is executed. This function is given the response data to act on. For information on ways to interpret and manipulate the response data, see the $.ajax function discussion in Chapter 7.

The semantic flag forces strict semantic ordering at the expense of execution speed. For more information, see the .formToArray() discussion later.

If resetForm or clearForm is set to true, the corresponding action will be taken before the success callback (if provided) is executed. For more information on these actions, see the .clearForm and .resetForm method discussions later.

If the form being submitted contains file upload fields, the file data will be properly uploaded using the multipart/form-data MIME type. No further action needs to be taken.