HTML Forms to AJAX Forms The Easy Way

Published 12th January 2010

For a while now I’ve wondered if there is an easy way to “AJAXify” forms without taking away from the semantics and functionality of a normal HTML form. So I came up with a simple solution powered by jQuery. The main aim here is to be able to just drop the javascript on top of the HMTL form in a progressive enhancement style so that the underlying HTML form would work even if the javascript is turned off.

The HTML

So first off lets create a simple HTML form to demonstrate what we are doing.

<div id="message"></div> <form id="html-form" action="process.php" method="post"> <label for="user">Name</label> <input id="user" name="user" type="text" size="40" value="" maxlength="50" /> <label for="email">Email</label> <input id="email" name="email" type="text" size="40" value="" maxlength="50" /> <label for="web">Website</label> <input id="web" name="web" type="text" size="40" value="" maxlength="50" /> <input id="submit" type="submit" value="Login" class="button" /> </form>

Fairly straight forward I hope. This form would POST the information to process.php which we will see later. Anyway the point is that this is a working HTML form.

The Javascript

So here is the interesting part. Here we are overriding the form’s submit event so that it will use the AJAX post rather than the normal POST.

$(document).ready(function(){ $("#html-form").submit(function() { //Do the AJAX post $.post($("#html-form").attr("action"), $("#html-form").serialize(), function(data){ //do stuff here... }); //Important. Stop the normal POST return false; }); });

As you can see we are doing a few things here.

  • First off we are using jQuery’s submit event to override the normal HTML submit. The important part here is that we return false at the end of this function to stop the normal form submitting.
  • Inside this event we do the AJAX post using jQuery’s $.post function. The first parameter is the URL where the POST is to be sent. In this case we just get it from the form’s “action” attribute. The second parameter is the data to be sent in the request. We use the serialize() function here to collect the data for us. Nice and simple. Finally we are defining the callback function which gets triggered when the request is complete.

So as you can see the few tweaks we have made with the javascript keep it very flexible and it means we can use almost the same code for every form we want to “AJAXify”. Nice.

The Server Side

Just as a side note you might be thinking “so what do I have to change on the server side of things?”. Well that’s a good question. Normally you would redirect to a page with some kind of feedback message. Now however you want to only echo the feedback messages and let the javascript deal with how you display the response. For example we could do this with the javascript:

$('#submit').val('Logging In...'); $.post($("#html-form").attr('action'), $("#html-form").serialize(), function(data){ $('#submit').val('Login'); if(data == 'success'){ $('#message').html('Successfully Completed the Form').removeClass('error').css('visibility','visible'); } else { $('#message').html('Error: ' + data).addClass('error').css('visibility','visible'); } });

This would show up the nice error messages returned by the PHP in the #message div. If there were no errors it displays a useful success message.

So in the PHP what we could do is separate the AJAX responses from the normal responses using the following code:

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { //Do AJAX reply's in here } else { //Do normal form processing here }

Conclusion

So there we have a fairly simple way of “AJAXifying” our HTML forms using some clever javascript.