Easily upgrade your forms to AJAX

By my standards no website should still use traditional webform GET or POST requests to transfer data to the server. Through AJAX, form data can be sent way faster, since only the necessary data is sent back and forth to the server. Thanks to the hard work of some individual developers, using AJAX to transfer data from html forms has been streamlined and has become very simple. I will demonstrate this by creating a comments form, which will transmit data to the server using the Prototype JavaScript Framework, developed by Sam Stephenson. The data will be processed on the server side and return data to the original html page, where it is displayed.

The Prototype JavaScript Framework is a javascript package containing several very useful functions for occasional JavaScript developers. The two key objects for transmitting data to and from the server are

  • Ajax.Request: Sends form data to the server and stores the response in a local JavaScript variable
  • Ajax.Updater: Sends form data to the server and displays the response in a div

For this example I will use the Ajax.Updater function. The first step is to download the latest Prototype JavaScript Framework .js file from the Prototype Homepage. Include this file in your html file:

<script src="prototype-1.3.1.js" type="text/javascript"></script>

Next let's create a simple html form. The only thing out of the ordinary here is that the form tag doesn't have an action. Instead I added a regular (not type submit) button, and added the onClick event handler to call the javascript function send(). Ignore the DIV tag for now.

<div id="updateDiv">
<form id="commentsForm">
<input name="name" type="text"><br>
<textarea name="comment" cols="20" rows="3"></textarea><br>
<input name="sendbutton" type="button" value="Send" onClick="send();">

Now it's time to do some magic. The function send() is called whenever the form button is clicked. In order to transmit all the form information to the server, we need to add up all the form values to name/value pairs. We could do this by hand, but Prototype comes with a function to make it a lot easier for us, Form.serialize(). I supply this function with the parameter $('commentsForm'), which uses another Prototype function $(). This function looks up page elements by their DOM id. Now that I have the parameters that I want to send to the server, I create a new Ajax.Updater object. The following variables are passed in:

  • The first variable is the name of the DIV in which we want to display the data that is returned from the server.
  • The second variable is the filename of the server side script that we want to execute. In this case I used a sample PHP script.
  • The third variable is an array of variables. Here we tell the script transfer data asynchronously (otherwise the browser would freeze until the data is transferred - exactly what we are trying to avoid). We also supply the script with the variable that contains our serialized values from the form.

<script type="text/javascript">
function send(){
var params = Form.serialize($('commentsForm'));
new Ajax.Updater('updateDiv', 'submit.php', {asynchronous:true, parameters:params});

On the server side all I do in this case is return a thank you statement. For this example submit.php only contains one line:

<?= "Thank you for your comments, ".$_POST['name']; ?>

This is quite worthless and in your case would be replaced with whatever you wanted to do with the information from the form. This could be a formmail, database operation, or whatever else application you are writing. This file will return html code or plain text, which will then be displayed in the DIV with the id updateDiv. Earlier I wrapped the form in this DIV, so that when the AJAX request is completed, this form is replaced with the thank you comment from the submit.php file.

This is it. The only true difference between creating a form that handles data on a new page using traditional GET and POST methods, and using AJAX, is to include the .js file and write a send() function that creates the Ajax.Updater function. This little bit of extra work is well worth the decrease in response time when submitting the form. Especially web-based applications, such as CRM systems, will benefit largely from using this technique.

Try this script:

Related Blog Entries

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Hi, the informations is very good. I was looking for a example like this
# Posted By colpas | 7/13/07 1:16 PM
Hi! Firstly, excellent script, it is just what I need! Second, is there any way to use this script on two forms on the same page?

Thanks again
# Posted By Charlie | 8/14/07 5:22 AM
You can add as many forms as you want. Just be sure to give each form and DIV a unique ID and reference the corresponding item from JavaScript.

# Posted By Julian | 8/14/07 8:53 AM
Excellent - I've added two forms to the same page successfully.

Thanks again for your great work.
# Posted By Charlie | 8/14/07 9:40 AM
Hi Julian, thanks for an amazingly simple easy script! I have an existing form which uses ajax validation on submit: <input type="submit" value="Submit" />.
How would I incorporate your script so that after successful validation the results would display in the updated div using the send() function?

Thanks again.
# Posted By Anon | 8/31/07 3:57 AM
Very Nice!!
# Posted By Dino | 10/5/07 1:42 PM
Grate thing, but I have problems with div update in FF2 browser, with IE6 and 7 work perfect, also in Opera.
Someone have the answer?
# Posted By Vadim | 11/13/07 7:41 AM
Sorry guys, it works fine :) even in firefox.
# Posted By Vadim | 11/14/07 11:42 PM
waw,excellent. congratulation sir
# Posted By Houba | 1/17/08 7:14 AM
man! if it works, i'm gonna kiss you!!!
thanks! well documented, nicely implemented.
Thanks for sharing. Good job!
# Posted By guillem | 2/20/08 10:35 AM
Hey! Me again!
It worked!!! Thanks again!!!
# Posted By guillem | 2/20/08 11:12 AM
Hey! Me again!
It worked!!! Thanks again!!!
# Posted By guillem | 2/20/08 11:12 AM
Hey! Me again!
It worked!!! Thanks again!!!
# Posted By guillem | 2/20/08 11:12 AM
Please use unobtrusive javascript:

document.observe('dom:loaded', function() {
Event.observe('submitButtonId', 'click', function() {
var params = $F('contactForm');
new Ajax.Updater('updateDiv', 'submit.php', {asynchronous:true, parameters:params});

# Posted By Nikolaas | 2/28/08 5:54 AM
Good call on attaching it to the DOMready state. Although I'm not sure the original state isn't unobtrusive, since any browser without Javascript wouldn't pick up on the onClick parameter. Either way, the FORM tag would still need an Action parameter.
# Posted By Julian | 2/28/08 7:55 AM
Hey man your example helped me a lot to learn how to submit a form using AJAX.thanks for giving this excellent help.
# Posted By coderbari | 3/21/08 8:50 AM
how can i add a preloader with this?
# Posted By bet | 7/1/08 6:20 PM
Any ideas on how to get server-generated variables from form information? Specifically, I want to use Ajax.something to check for file size and type before the user uploads it.
# Posted By emptycrawford | 7/29/08 3:11 PM
Thanks. It doesn't work with input type file - image uploading
# Posted By netmastan | 8/23/08 4:52 PM
Thank you so much for this. You saved me a lot of time.
# Posted By Mike Kieffer | 8/18/10 8:25 PM
BlogCFC was created by Raymond Camden. This blog is running version 5.7.002.