Tutorial: AJAX with jQuery

Posted on 1 Comment

jQuery is a very powerful JavaScript framework, and to put in their own terms, is The Write Less, Do More JavaScript library. jQuery’s slogan indeed holds true to its claim, as you’ll discover as soon as you start coding using jQuery. Although jQuery has an extensive set of API and a collection of many functions in its arsenal, I would be concentrating more on the AJAX capabilities of jQuery in this tutorial.

Most of the modern websites, irrespective of whether they offer a simple or a complex interface, usually use AJAX for some task or the other. While designing in order to cater to today’s needs, it becomes almost indispensable to use AJAX to make the end-user experience faster and more pleasant. So, if you had been deferring the use of AJAX till now owing to it’s complexity in raw JavaScript, here is your chance to start using it with utmost ease.

It is really amazing to see how much simplified AJAX is with jQuery. The developers have seemingly (and painstakingly) done a lot of hard work behind the scenes to make it easy for the web developer to implement even the most complex JavaScript concepts, including AJAX.

For the purpose of demostrating AJAX, I’ll be making use of a simple web application (that I designed using HTML, PHP, jQuery, CSS and MySQL). I call it the Albums Database.


This is the main page, the page the the end-user is going to see. Below is the complete code for this page, and even below that is a brief explanation of it.

We start with the <head> tag. First, we mention all the external scripts and stylesheets that we are going to use with our page. The scripts include a latest copy of jQuery JS file, jQuery UI (optional), AjaxUpload plugin for jQuery, and our own custom JS file. The stylesheets include our own CSS code and jQuery UI’s CSS file (optional).

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
     <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
	<title>Albums Database</title>
	  <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
	  <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
	  <script type="text/javascript" src="js/ajaxupload.3.5.js"></script>
	  <!-- Custom JS code that utilizes APIs of some other JS file (jQuery in our case)
		 should be referred to in the head section after the file containing APIs -->
	   <script type="text/javascript" src="js/javascript.js"></script>
	   <link type="text/css" href="css/ui-lightness/jquery-ui-1.7.2.custom.css" rel="Stylesheet" />
	   <link type="text/css" href="css/style.css" rel="Stylesheet" />
	<h2 id="block" style="color: white; background-color: purple; padding: 20px; margin:0;">
		Welcome to Albums database.
	<p><a id="new_album" href="#">New Album</a></p>
	<form id="new_album_form" style="background: #F3F4BA; padding: 10px; margin: 10px; display: none;">
		<table width="100%">
			<tr><td width="100px">Name:</td> <td><input id="album_name" type="text"/></td></tr>
			<tr><td width="100px">Artist:</td> <td><input id="album_artist" type="text"/></td></tr>
			<tr><td width="100px">Year:</td> <td><input id="album_year" type="text"/></td></tr>
			<tr><td width="100px">Cover:</td> <td><input id="album_cover"> <img id="loader-2" style="display:none;" height=16 width=16 src="loader-yellow-bg.gif"/></td></tr>
		<br><input type="submit" value="Create"/> 
		<img id="loader-3" style="display:none;" height=19 width=220 align="top" src="loader-long.gif"/>
		<div id="create_album_result" style="color:green; display:none;"></div>
		Search for albums:
		<input id="userinput" type="text"/> 
		<img id="loader" style="display:none;" height=16 width=16 src="loader.gif"/>
	<div id="results">

In the main body, we start by displaying a sweet little header. Below the header is a link New Album which, as the name implies, will display a form to create new albums and post them to our database. Below this link is a form that has 4 fields required to be filled to create a new album. By default, this form is hidden and will be shown to the user only after the above link is clicked. After the form, we have a “search box” which lets the user search for existing albums in the database, and the searching is automatically done as the user types into this box. The search results are then displayed below the search box. Magic, you say? It’s AJAX actually.


Here comes the main file of our whole web app. This file contains all the code in JavaScript that will be used to control the behavior of various elements present in our index.html page. Of course, we make use of jQuery to write our JS code in it.

$(document).ready(function() {

The first step is to make sure that index.html has fully loaded in browser of the user before our JS code can be applied to it. This reduces any chances of error or misbehavior on the part of our coding at the user’s end.

 /* Convert the input with id 'album_cover' into AJAX uploader */
new AjaxUpload('album_cover', { action: 'upload.php', 
					onChange: function(file) {$('#loader-2').show();}, 
					onSubmit: function(file, ext) {
						if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
							// extension is not allowed
							alert('Error: invalid file extension');
							// cancel upload
							return false;
					onComplete: function(file) {$('#album_cover').val(file); $('#loader-2').hide();}

Now, using the AjaxUpload plugin for jQuery, we associate the functionality of uploading images through AJAX with the Cover field of our new album form.

/* Show/hide the create new album form when 'New Album' link is clicked */
$('#new_album').click(function() {

Next, we specify that when the New Album link is clicked, the corresponding form should be displayed (with effects) if hidden or hidden if displayed. That is, we toggle the display state of the form.

/* Post the entry of the new album into the database, using AJAX, when the form is submitted */
$('#new_album_form').submit(function() {
	if ($('#album_name').val() != '' && $('#album_artist').val() != '' && /^([0-9]{2}|[0-9]{4})$/.test($('#album_year').val()) && $('#album_cover').val() != '') {
		$.post("create.php", {album_name: $('#album_name').val(), album_artist: $('#album_artist').val(), album_year: $('#album_year').val(), album_cover: $('#album_cover').val()}, function(data){
	else {
		alert("Please fill in all the details and fill them correctly.\nYear can be only 2 digits or 4 digits long.");
	return false;

After that, we specify the code to be executed when the user submits the form. We start by unhiding an originally hidden animated ‘loader’ image to give the user an illusion of something going on behind the scene (that is, the form submission process starting). Then we put a if condition to check whether all the form fields were filled in and if the Year field was filled in correctly (we use regular expressions for this; the year should be 2 or 4 digits long only). If the form was filled up fine, we use the jQuery AJAX method $.post to submit the filled up form into the database. Our handler script in this case if create.php. After the form submission process has completed, we again hide our animated loader image.

/* Start searching the database, using AJAX, when the user has typed at least 2 characters */
$('#userinput').keyup(function() {
	if ($(this).val().length >= 2) {
		$.post("search.php", {searchterm: $('#userinput').val()}, function(data){
	else {
	return false;

The next part of our JS code deals with the search box. We specify that as soon as the user types in the third character (whatever it be), the $.post method executes, making use of the handler script search.php this time. The fetched search results are then displayed in the <div> area with id results


Takes in just one POST variable called “searchterm” and uses it to query our MySQL database to find what the user might be looking for. It then prints the search results, in HTML form.

	/* Connect to the database */
	include 'config.php';
	$connection = mysql_connect("$DB_HOST","$DB_USER","$DB_PASSWORD");
	/* Query the database for searching */
	$search_query = "SELECT * FROM albums WHERE album_name LIKE '%$_POST[searchterm]%' OR album_artist LIKE '%$_POST[searchterm]%' OR album_year LIKE '%$_POST[searchterm]%'";
	$search_result = mysql_query($search_query) OR die(mysql_error());
	/* Display the search results */
	$counter = 1;
	print "<table width=\"100%\" cellspacing=\"10px\" cellpadding=0>";
	while($newArray = mysql_fetch_array($search_result)) {
		// Display alternate gray-white search result entries
		if($counter%2==1) {
			$class = "gray-box";
		else {
			$class = "white-box";
		$name = $newArray[album_name];
		$artist = $newArray[album_artist];
		$year = $newArray[album_year];
		$cover = $newArray[album_cover];
		print "<tr class=\"$class\">";
		print "<td valign=\"top\" width=\"100px\"><img width=100 height=100 src=\"$cover\" style=\"float:left;\"/></td>";
		print "<td valign=\"top\"><b>Name:</b> $name<br><b>Artist:</b> $artist<br><b>Year:</b> $year</td>";
		print "</tr>";
	print "</table>";


Takes in the four POST variables – album_name, album_artist, album_year and album_cover – and uses them to create a new entry for the submitted album into our MySQL database.

	/* Connect to the database */
	include 'config.php';
	$connection = mysql_connect("$DB_HOST","$DB_USER","$DB_PASSWORD");
	/* Values received */
	// mysql_real_escape_string() prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a. 
	$album_name = mysql_real_escape_string($_POST[album_name]);
	$album_artist = mysql_real_escape_string($_POST[album_artist]);
	$album_year = $_POST[album_year];
	$album_cover = $_POST[album_cover];
	/* Manipulate the database */
	$insert_query = "INSERT INTO albums (album_name, album_artist, album_year, album_cover) VALUES ('$album_name', '$album_artist', $album_year, 'images/$album_cover')";
	$insert_result = mysql_query($insert_query) OR die(mysql_error());
	print "<br>Album created! ";
	print "<a href=\"javascript:ResetForm();\">Create New</a>";


Simple PHP scripts that handles where and how the files uploaded, using the Cover field of the new album form, are placed on the server.

        $uploaddir = 'images/';
	$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
	if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
  		echo "success";
	else {
  		// Otherwise onSubmit event will not be fired
  		echo "error";


Included in all our PHP files and stores the variables containing MySQL database information, like DB name, host name, username and password.

// ** MySQL settings ** //
$DB_NAME = "albumdb";    // The name of the database. albumdb is only an example. So, replace it with the name of your database.
$DB_USER = "username";     // Your MySQL username. In most cases root works, but it highly not recommended.
$DB_PASSWORD = "password"; // ...and password. The default password for root is none.
$DB_HOST = "localhost";    // 99% chance you won't need to change this value. 


Our custom CSS file. Short and precise.

.yellow-box {
	background-color: yellow;
	margin: 10px;
	padding: 20px;
	display: none;
.gray-box {
	background-color: #efefef;
.white-box {
	background-color: white;

albumdb MySQL database

This is the structure of that database used with this web app, with albums as the only table.

album_id - int(11) [ PRIMARY KEY auto_increment ]
album_name - varchar(100)
album_artist - varchar(100)
album_year - int(4)
album_cover - varchar(100)


Have a look at the final thing (our web app) yourself. The demo is here.


Click here to download the entire web app, excluding the SQL database (you’ll have to create it yourself based on the structure mentioned above).

1 thought on “Tutorial: AJAX with jQuery

  1. very nice. keep it up.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.