Developing Web Applications with Ajax, Part 4 | WebReference

Developing Web Applications with Ajax, Part 4

Developing Web Applications with Ajax, Pt. 4

In part four of this series of developing Web applications with Ajax, you'll learn how to submit information through forms without reloading the page. This can be used for a variety of purposes. Let's begin with the form's HTML, and then we'll move onto adding the JavaScript for submitting a form with Ajax.

Please keep in mind that throughout this article I will be using PHP to process server-side requests from JavaScript, so the code explained in this article will need to be saved as a file with a .PHP extension and must run on a PHP-enabled server. This will not work on your local hard disk.

This form submits to the following PHP file, ajax_output.php, which takes the data and outputs it.

The output is a DIV that contains a couple of paragraphs. If the name field is filled in, it will output "Hello, [your name]." If the hair field is filled in, it will say "You have [hair color] hair!" If you put in both, it will output both messages in the same DIV.

Now it's time for the JavaScript. Following is the JavaScript code and an explanation.

You first notice the JavaScript tag. This is a function that is evoked when the form is submitted (the onsubmit event handler in the form is what calls the function). The function begins by creating an XMLHttpRequest to send data to the form's action (ajax_output.php). Next, we loop through each and every form element and concatenate them with ampersands so that the data can be cleanly sent to the action. After that, we set up an onReadyStateChange function that populates the "insert" DIV with the data that ajax_output.php sends back. Then we open the form's method (ajax_output.php), either POST or GET (we're only set up for POST to work with our current ajax_output.php script) and the action (ajax_output.php). We set the request header so that JavaScript sends form urlencoded data to ajax_output.php, and then we tell JavaScript to send the form data to the action.

Conclusion

This script is very versatile and is useful in many situations, since you can put any form elements within the form above and the data will be POSTed to the form's action without reloading the page. You need simply modify the form's action file to reflect changes of input names in the form and how to handle that data.

About the Author

Jonathan Fenocchi is a Web developer who primarily works in the fields of Web Design with CSS, client-side scripting with JavaScript, and server-side scripting with PHP. His web site is located at: http://www.slightlyremarkable.com.


Created: November 15, 2005
Revised July 19, 2006

URL: http://webreference.com/programming/javascript/jf/column15/1