2009
07.17

Hi everyone!

It’s been a long since my last post, and I hope I can start posting more often.
Today I’m bringing you a small tutorial of how you can do a simple form that’s uses ajax and jQuery to do the job you want.

We’ll not be focusing on best practices or teaching any CSS. I’ve upload a live example where you can see it in action and also get the source code. If you’re interested, just click here. Feel free to comment or e-mail about doubts or suggestions. They are all going to be welcome and answered ASAP.

So, the first thing we’ll be doing is to link the jQuery file, that you can download here. After the download, put it inside your project’s directory.


In my case, I’ve created a very suggestive directory do store my JavaScript files called “js”, one called “css” to store (guess!) my CSS files and another one called “imgs” to store (hard, huh?) my images.

Now we’re going to create a simple form structure. I’ve built it in order to submit the name, e-mail and a message of the user. All these fields will be required, and this validation will be made on the server side. Feel free to add some JavaScript to validate it on the client side too (which is a very nice idea).

Loading Sending request...

The last row, as you can see, already has the loading image and also the message. But we don’t want to show it to the user yet. In order to do it, be sure to set the CSS for the TR “status” as “display: none”.

Now let’s go to the jQuery part. I’m going to assume that you already have some experience using it.

If you don’t have, my suggestion is for you to visit and watch all the videos of the “jQuery for Absolute Beginners”, from In The Woods Blog, by Jeffrey Way. It really helped me out, and that’s why I strongly recommend you to go there.

So, basically what we are going to do is:

1 – Capture the click on the button;
2 – Show an image and a text to say that the request is being sent;
3 – Disable the submit button, so that the user won’t click again until is finished;
4 – Get all the data provided and send to the PHP file (or whatever we want);
5 – Once all the actions are done, the PHP file returns something, we capture it and show the return message;
6 – Enable the submit button again.

For steps 1, 2 and 3 we’ll have:

  $(function(){

    	$('#submitButton').click(function(){
        	if($('#status').css('display') == 'none')
        	   $('#status').toggle();

    		$('#statusImage img').attr('src', 'imgs/ajax-loader.gif');
                $('#statusImage img').attr('alt', 'Loading');
                $('#statusMessage').html('Sending request...');

    	        $('#submitButton').attr('disabled', 'disabled');
// to be continued...

This will make the “#status” show up, then will change the image’s “src” and “alt” attributes to loading (ok, it was already like this, but after the first time you click it won’t be).

It will fill the row with some info, telling the user that the request is being sent. After that let’s get all the data provided and send to the PHP using the jQuery’s ajax way. I think that the code itself is very simple, but if you have doubts or if you want to know more about the other ajax options, just visit the method documentation.

//continuation
// steps 4 and 5
var name = $("#name").val();
var email = $("#email").val();
var msg = $("#msg").val();

$.ajax({
url: 'doSomething.php',
type: 'POST',
data: 'name=' + name + '&email=' + email + '&msg=' + msg,

// to be continued ...

Now that we have set the ajax options, we have to capture the response provided by the “doSomething.php” and show to the user.

// continuation

success: function(response){
    	    	   if(response == 'success') {
    	    		   $('#statusImage img').attr('src', 'imgs/success.png');
    	    		   $('#statusImage img').attr('alt', 'Success!');
    	    		   $('#statusMessage').html('The message was sent successfully!');
    	    	   } else {
    	    		   $('#statusImage img').attr('src', 'imgs/error.png');
                           $('#statusImage img').attr('alt', 'Fail!');
                           $('#statusMessage').html(response);
    	    	   }

    	           // step 6
    	           $('#submitButton').removeAttr('disabled');

    	    	}
    	    });
    	});
    });

Now we are going to make the PHP file “doSomething”. As I said before, it’s just a simple PHP file to represent the action you want to do. It simply checks if all the fields were filled, return a success message if so. Else, it returns a message that would be your error.

/*
 * This file does nothing, basically.
 * Here you specify whatever you want to do with your data.
 */

if($_POST){
	if( $_POST['name'] != '' && $_POST['email'] != '' && $_POST['msg'] != ''){
		echo 'success';
		return;
	} else {
        echo 'Name, E-mail and Message fields must be filled.';
        return;
	}
}
echo 'What do you want to $_GET here?';

That’s pretty much it.
If all the fields were filled or not, it returns a message and that will cause jQuery to fill the last table row with a nice image and a message so that the user knows what happened :)

Thank you for reading!
I’ll be waiting for your comments and doubts!

No Comment.

Add Your Comment

Comments are closed.