Form Submission ajaxSubmit()

Ok, so assume you have a standard form. You need to do some error checking on the form before submission finally takes place. In the past, I've found myself writing JS form field validation, then writing server side field validation as well. In playing with jQuery and AJAX, I've put together a nice package that will do server side validation, without leaving the form, thereby removing the need for javascript validation completely.

The way this works uses a php post page, which accepts a parameter to determine that the form was submitted via ajax, then returns either a XML string, or a redirect to the calling page with the error(s) attached.

First off, the form, Create Account (#frmCreateAccount)

Pretty normal form, would connect to a database to ensure unique email addresses. I've disabled the db lookup, but test@example.com should provide a "Email Address already used" error.

Account Information

Required fields marked with *

Your email address will be required for log in. Try: test@example.com

Choose your password wisely.

Type your password again, just to make sure.

This will be used to tell people who you are.

Where are you from? ex: "Glastonbury, CT," "Eastern Time Zone," "North America."

Add some jQuery

Connect the Plug In:

$(document).ready(function(){ $("#frmCreateAccount").ajaxSubmit(); });

Plug In Source:

$.fn.ajaxSubmit = function(e) { /* Change a form's submission type to ajax */ this.submit(function(){ var params = {}; $(this) .find("input[@checked], input[@type='text'], input[@type='hidden'], input[@type='password'], input[@type='submit'], option[@selected], textarea") .filter(":enabled") .each(function() { params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; }); $("body").addClass("curWait"); $.post(this.getAttribute("action") + "?call=ajax", params, function(xml){ $("body").removeClass("curWait"); strError = "Unable to submit form. Please try again later."; oFocus = null; $("AjaxResponse", xml).each(function() { strRedirect = this.getAttribute("redirecturl"); strError = this.getAttribute("error"); oFocus = this.getAttribute("focus"); }); if (strError.length == 0) { window.location = strRedirect; } else { alert("The following errors were encountred:\n" + strError); $("div.formErrors").html("<h3>Error<\/h3><ul>" + strError.replace(/(\t)(.+)/g, "<li>$2<\/li>") + "<\/ul>").filter(":hidden").fadeIn("normal"); if (oFocus) $("#" + oFocus).get(0).focus(); } }); return false; }); return this; }

Presto, this form now on submit:

this.submit(function(){
  1. Collect the form fields into a params object var params = {}; $(this) .find("input[@checked], input[@type='text'], input[@type='hidden'], input[@type='password'], input[@type='submit'], option[@selected], textarea") .filter(":enabled") .each(function() { params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; });
  2. Add a "curWait" class to the body, giving a hourglass symbol $("body").addClass("curWait");
  3. Post, via AJAX to the current form's action ("dbFormSubmission"), adding a "?call=ajax" to the URL $.post(this.getAttribute("action") + "?call=ajax", params, function(xml){
  4. Posting page will do validation as per normal, with the new call=ajax, it will respond to the calling page with XML data instead of a redirect

Upon completion of submit, the page will process the response:
Response Sample

<AjaxResponse error="&#9;Password is a reqiured field.&#10;&#9;Name is a reqiured field.&#10;&#9;Location is a reqiured field.&#10;" focus="pwdAccountPassword" redirecturl="formSubmissionSuccess.php" />
  1. Set variable defaults strError = "Unable to submit form. Please try again later."; oFocus = null;
  2. Read the XML $("AjaxResponse", xml).each(function() { strRedirect = this.getAttribute("redirecturl"); strError = this.getAttribute("error"); oFocus = this.getAttribute("focus"); });
  3. If there is no error, redirect to the new URL if (strError.length == 0) { window.location = strRedirect;
  4. Otherwise, pop an alert box with the error, and populate the div.formErrors with the error as well, doing a fadeIn the first time the form is submitted. } else { alert("The following errors were encountred:\n" + strError); $("div.formErrors").html("<h3>Error<\/h3><ul>" + strError.replace(/(\t)(.+)/g, "<li>$2<\/li>") + "<\/ul>").filter(":hidden").fadeIn("normal"); Also, we'll attempt to regain focus on the appropriate field if (oFocus) $("#" + oFocus).get(0).focus(); }
  5. That's It!
Myles Angell
June 17th, 2006