Automatic conversion of web form submissions to AJAX with jQuery

Improve your form submissions with this handy trick

By  

Source: Török Gábor

If you’ve got a data heavy web application, chances are you’re doing a lot of form posting. Here is a quick solution to automatically convert all of your full form posts into quick and user friendly AJAX posts.


Note: Because we're not actually posting to an endpoint you may have to click through to the JSFiddle site for the script to complete.

Why you should

The benefits that come from doing this are:

  • Improved user experience

  • Reduced HTTP bandwidth

  • Increased perception of site speed

Setup

This jQuery code has a few requirements.

1) You must have 1 or more <form> elements on the page

2) Your form element must have a child element with classes of “form-actions” and “ajax-form”

3) Your form-actions element must have a child element with classes “btn” and “submit”


None of those requirements are concrete however, you can modify it easily to suite your needs.

In the example I’m also loading the Twitter Bootstrap library for some basic styling.

How it works

The code will search through every page it’s loaded on looking for a form element with a form-actions child which also has the ajax-form class. For each of the forms that match this selector, the element with the classes btn and submit will have its onclick event bound to the postData() function.

This function will dynamically determine the AJAX Post Url based on the action attribute of the form. It will then serialize the forms input data and perform an AJAX Post.

Any form in your application that you structure in this way will automatically be converted to an AJAX form. A nice and convenient trick.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

Ask a Question
randomness