Yesterday, PHPBuilder posted an article about sending a form using AJAX. This article shows how to post a simple form. But looking closely at the example, you can also see what the problem is using the plain XMLHttpRequest object and writing an implementation yourself.

First of all you to write some rather difficult javascript code. Next you need to completely rewrite your page, looking nor working like a normal HTML form. Last and most important, the function fetches values using getElementById(). This is not really very flexible, because you will need not only the form, but the function as well when you add a field.

Using an AJAX library can really help you here. Javeline TelePort has got a brand new method, which automatically creates a HTTP post request of a form and sends it to the server.

We’ll start with a plain HTML form, without AJAX. Like always, the URL is in the action attribute. To keep the page open, the result will appear in a new window.
[SOURCE::jtp_submitform/without_ajax.html::xml]
See it working

Now lets add some AJAX. We need to include the TelePort library, which is the communication only package of Javeline PlatFrom.

<script src="teleport_sdk/teleport_post.js" type="text/javascript"></script>

AJAX is asynchronous, so we do need to define a function to handle the result of the call. We’ll add a getHttpRes() function which pretty much does the same as the one in the PHPBuilder article. We’ll also add a reset function to place back the form. (Requesting the form with AJAX just doesn’t seem useful.)

function getHttpRes(msg, state, extra){
	if(state != __RPC_SUCCESS__) return alert("Could not connect to server");
 
	if (!self.orig_div1) self.orig_div1 = document.getElementById('div1').innerHTML; // Save to original content for reset
	document.getElementById('div1').innerHTML = msg + "<br/><input type='button' onclick='reset_div1();' value='Try again' />";
}
 
function reset_div1() {
	if (self.orig_div1) document.getElementById('div1').innerHTML = self.orig_div1;
}

Pushing the submit button on the form would still do a normal post, instead of doing an AJAX call. This is however where you can really see the use of using a library. We can simply add a onsubmit event, letting TelePort send the form and then return false to cancel the post event.

<form ... onsubmit="new POST().submitForm(this, getHttpRes); return false;">

That all there is to it. Plus a bonus: when javascript is disabled, the form will still work.
[SOURCE::jtp_submitform/with_ajax.html::xml]
See it working

For you see it believing people out there. Here is an example showing a more advanced form. The javascript didn’t need to be changed at all to make this work.
[SOURCE::jtp_submitform/advanced_ajax.html::xml]
See it working

I hope I managed to convince you to use a library for AJAX, instead of doing it all by yourself, preferably Javeline of course, but make up your own mind there.

Download the code