Taken from a mailing list answer by Klaus Hartl
To make forms accessible with and without Ajax, I start with building the form as if I were building a standard form with its traditional submit and refresh the page behavior. Think of JavaScript being disabled.
This handling goes all into the else block of my example because there will be no "X-REQUESTED-WITH" header in the http request (I come to that later). You are simply sending back a complete page as response to the form submit.
In the next step I so called "hijax" that form to enhance the user experience a little bit. Such a technique is also refered to as "Progressive Enhancement".
That means:
1. I will pick up the form and switch off the default submit action by adding my own event handler.
$('#hijax-me').submit(function() {
return false;
});
2. Then add some logic to gather all the form values and transmit it via Ajax in the background, while you are pickinq up the form‘s action as well:
$('#hijax-me').submit(function() {
// stupid IE returns an object for the forms action
var url = this.attributes['action'] &&
this.attributes['action'].nodeValue || this.getAttribute('action');
// works fine with very simple forms, just as an example
var data = $('input', this).serialize();
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: function(response) {
// show message for example
}
});
return false;
});
$.ajax calls the same page as if you were submitting the page in the traditional way. But because jQuery's $.ajax also adds a custom header to the request, of the form "X-Requested-With: XmlHttpRequest?" (same as Prototype if I remember correctly), you know in your page how it has been requested and can handle the request according to that. (in PHP via $_SERVERHTTP_X_REQUESTED_WITH?)
This happens in the if block in my example. You can now decide to only send back a part of the page (like only the markuped confirmation message to replace the form, or maybe sendback JSON or XML to be further processed on client-side).
As a result you still can have all your backend logic in one place and have a 100% accessible form with enhanced user experience if JavaScript is enabled. And in the end this means only a little more work to do, if at all.
jQuery's form plugin makes it even easier to do that, I think there is an $.ajaxSubmit function, that does all the stuff for you...
