How To Create Form Posts with Ajax | WebReference

How To Create Form Posts with Ajax

By Kris Hadlock

Digg This Add to

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.

The difference between this code and the standard Web form is that we're now including a couple JavaScript objects (which we'll discuss soon). We direct the form submission to a file called bridge.php and we catch the form submission with the onSubmit event where we call a JavaScript method and return a value of false, so the form doesn't submit as usual.

The two JavaScript objects that we include are Ajax and Post. The Ajax object is a custom object which I've created to handle Ajax requests and responses. (If you want to learn more about this object you can take a look at some of my beginning Ajax articles.) If you haven't downloaded the source code I've included the Ajax object code below.

The 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.