Now that Ajax is becoming a standard for handling interactions on the Web it's time to use it to update form submissions. In this article you'll learn how to create a reusable Ajax process which can be used with all forms. The source code for this article can be downloaded here and a live preview can be viewed here.
Starting With a Standard Web Form
A standard form includes a set of form tags with custom form fields, such as a name, city, state and so on. In order to successfully submit a form these form elements must have a unique name, so we can retrieve the value with a server-side language when the form is submitted. How we gather this information on the server-side is based on the method in which the form is sent, either a get or a post. Where we send it to is based on the action defined in the opening form tag and if it's left empty the page submits to itself. Listing 1 shows a standard Web form that submits to itself, uses the post method and sends a name and a message to the server on submission.
It's pretty straightforward and I'm sure that many of you know how to do this by now, but I think it's important to understand the basics when incorporating Ajax. In fact, if you understand how a standard Web form submits, Ajax can be incorporated without much effort. To do so, we need to catch the form submission and create the query string based on the values of the elements within the form.
Catching Form Posts
Catching a form submission is simple, all it requires is a forms onsubmit event. If we were to use the same form as before our code would look like listing 2.
post object will be the focus of the rest of this article; it's used to catch form submission, build a query string from form element values and make an XMLHTTP request through the Ajax object.