Mixed Media and Web Development.

Ajax with jQuery in 3 easy steps

Ajax with jQuery in 3 easy steps

I figured I would make this small tutorial for all of you curious about it. Pulling data from a database with ajax should not be feared. It is actually very simple. The majority of the work is in the server side part of the ajax. So for this tutorial I will show you how to check if a username exists in a database.

DEMO

Step 1
So lets start by adding the jQuery into the head of the page where the form is.

$(document).ready(function() {
	//Make sure the loading image is hidden.
	$('#loader').hide();
	//Blur is triggered when you leave the textbox.
	$('#username').blur(function(){
	  //Show the loader once blur is triggered.
	  $('#loader').show();

	  //Post will send the username value to the check page
      $.post("check.php", {
	    //sends the username value check.php?username=value
		username: $('#username').val()

		//grabs the responce from the check.php page
      }, function(response){

		 //This part is more style than function.
		 //The 400 gives the loader time to make it look like its doing something.
		 //The lower the number the faster the the result shows.
        $('#results').fadeOut();
        setTimeout("finishAjax('results', '"+escape(response)+"')", 400);
      });
    	return false;
	});
});

//id is results span and responce is the data
function finishAjax(id, response) {
  //hide the loader
  $('#loader').hide();
  //prints the results
  $('#'+id).html(unescape(response));
  //fade the results in
  $('#'+id).fadeIn();
} //finishAjax

Step 2
Now for the form. The only thing needed is a username textbox, the loader image and the spans.

Username: Password:

Step 3
Now for the server side.

if ($_POST['username']) {
        $username = stripslashes($_POST['username']);

		// Make a MySQL Connection
		mysql_connect("localhost", "username", "password") or die(mysql_error());
		mysql_select_db("database") or die(mysql_error());

		// Retrieve all the data from the usercheck table
		$result = mysql_query("SELECT username FROM usercheck")
		or die(mysql_error());  

		$row = mysql_fetch_array( $result );

		// Print out the contents of the entry
		if($row['username'] == $username){
			echo 'This username is taken.
Please choose another.';
		 }else{
			echo 'Available!';
		}
}

And that is pretty much it. Enjoy.



Leave a Reply