Simple Ajax example for timeout, statuscode, error and abort using jQuery with PHP

Now a days lots of website are using jQuery Ajax to retrieval the data without refreshing the webpage, previously we have to code for XMLHttpRequest or ActiveXObject object for different browsers.

Now jQuery changed with their library which will support lots ajax method like $.ajax, $.getJson, $.post and much more. Today we are going to focus on $.ajax method.

How Ajax works

1) create XMLHttpRequest object and send httprequest to server.
2) process the httprequest, send the response to client browser.
3) getting the data using javascript and display in client browser.

<!-- include jQuery library -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="javascript">
// global varaible will use to check the ajax call
var ajaxObject = null;

// ajaxcall function will handle ajax call
function ajaxCall() {
	
	// static parameter send the value to server
	var query = 'yes';
		
	// checking ajaxObject varaible null or not,
	// If the ajaxObject is not null then it will abort the current ajax call
	// and reinitialize the ajaxcall assign the ajaxObject null
	
	if(ajaxObject!=null) {
		ajaxObject.abort();
		$("#spnStatus").html("ajax abort and reinitialized");
		ajaxObject =  null;
	}	

// creating ajax call
	ajaxObject = $.ajax({
		
		// setting the url
		url:"data.php",
		
		// sending the value in parameter of query
                // change the '' to query for timeout error
		data:{query:''},
		
		// setting timeout for 5 seconds, if the server takes 
		// more the 5 seconds it will terminate the ajax calls
		timeout:5000,
		
		// checking the status for the success message,
		// assigning the response data from server to spnStatus tag		
		success:(function(response,responseStatus) {
			if(responseStatus=='success') {
				$("#spnStatus").html(response);
			}
		}),
		
		// we are checking the code for the file exists or not
		statusCode:{
			404:function() {
				$("#spnStatus").html("Sorry file not found!");
			}
		},
		
		// error function  we are checking timeout, 
		// if its taking more than 5 seconds from server to response
		// send the error message to spnStatus tag
		
		error:function(xhr,textStatus,errorThrown) {	
			//$("#spnStatus").html("Error : "+xhr.error+"_"+textStatus+"_"+errorThrown);
			if(textStatus=='timeout') {
				$("#spnStatus").html("Error : Current call has been timeout");
			}
		}
	});	
}
</script>

Creating spnStatus div tag to display data and error msg,
calling the ajaxCall function in href

<div id="spnStatus"></div><br />
<a href="javascript:ajaxCall();">Click to start Ajax Call</a>

create a server side file data.php

<?php
        # this query will send delay response to client browser
	if($_GET["query"]=='yes') {
		sleep(7);
	}
	
	echo "Welcome to Codeasearch.com";
?>

[ Download ] | [ Demo ]