Plugin parade #2: form

You started with a simple HTML form, maybe for registering new users. Now someone asked you to put all kinds of other stuff on that page, and you don’t want the user to reload all that when the form is submitted. But you also don’t want to gather all the input fields, serialize and send them via AJAX. So far, the browser did the serializing pretty well for you, and also you don’t want to change your server-side code.

In that case, and lots of others, you need the form plugin.

Form plugin source (contains detailed documentation)
Documentation on Visual jQuery (Plugins/Form), though a bit outdated

Similar to the metadata plugin, it has evolved from the jQuery mailing list. A lot of people have worked on it and it is currently maintained by Mike Alsup.

The form plugin provides several methods to submit your form via AJAX. The easiest one is ajaxForm():

$("#myformid").ajaxForm();

This replaces the normal browser submit with an AJAX submit: It registers for the submit event of the form (allowing the user to use the submit button or plain keyboard events), serializes all input fields inside the form, uses the action property as the URL to send the form to and the method property for the method (GET or POST).

Though what we are missing here is a way to display the response. Again the easiest aproach is to provide an expression that selects an element where the response is displayed. May sound complicated at first, but it isn’t:

$("#myformid").ajaxForm({
  target: "#responseContainer"
});

Here we select an element with the id “responseContainer” to display the response.

Maybe this is a bit too simple: You’d want some validation before the submit, and do a few actions after the submit, using the response. You also need to send the form to a different URL, to be able to return JSON instead of a full HTML page. We pick a few of the available options, and throw them together:

function pre(formdata) {
  if( !formdata.length ) {
    alert("Please fill out the form");
    return false;
  }
}
function post(response) {
  if( response.status != "error" ) {
    $("#reponse").html(reponse.message);
  } else {
    alert("Your form submission was not succesful");
  }
}
$("#myformid").ajaxForm({
  beforeSubmit: pre,
  success: post,
  dataType: "json",
  url: "ajax.php"
});

The pre function checks if there are any succesful elements, in other words, if anything at least one field contains something to submit. The post function checks the JSON response, allowing a different handling of succesful and failed submits.

Both the pre and post function are passed to the ajaxForm method as options. The dataType option is the same as for $.ajax(), it’s just passed through. We set it to JSON because we want to work with the response as JSON (eg. access response.status).

We also define the URL to submit the form to. This makes it easier for the server-side to distinguish between a normal and an AJAX submit. The more elegant version would be to check for the “X-Requested-With” HTTP header on the server-side.

The form plugin also provides very useful methods when working with other aspects of forms. You can use clearForm() and resetForm() to clear and reset forms. Getting the actual value of certain form fields can be quite complicated, caused why certain browser-differences. fieldValue() takes the burden to lift this issue from you. It even returns the correct value for option elements with no value attribute specified, which can be quite tricky in IE.

Update:
Mike pointed out some minor issues and an update: before and after callbacks are deprecated in favor of beforeSubmit and success, and the validation must be for “!formdata.length”, I forgot the invertion. The explanation for ajaxForm was inaccurate, that is fixed, too. Updated above. Thanks Mike!

-Jörn

No more comments.
  1. Muhammad Wasim

    Thanks alot… It really helped me