Jquery ajax ready states

When we send an ajax request through jquery, sometimes the request does not get response on time, and it gets aborted. In order to avoid it, we can set a timeout for the ajax request. Also, we can perform necessary actions for different ready states of ajax request.

An example:

 

$.ajax({
url: ‘ajax.php’,
type: ‘POST’,
data: { name: value },
beforeSend: function() {
// show a loading image
},
complete: function() {
// hide the loading image
},
success: function(data) {
//console.log(data);
},
timeout: 30000, // 30 seconds
error: ajaxError // handle error
});

// A sample function to  handle ajax errors:

function ajaxError(request, type, errorThrown)
{
var message = “Oops…\n”;

switch (type) {
case ‘timeout’:
message += “The request timed out.”;
break;
case ‘notmodified’:
message += “The request was not modified but was not retrieved from the cache.”;
break;
case ‘parsererror’:
message += “XML/Json format is bad.”;
break;
default:
message += “HTTP Error (” + request.status + ” ” + request.statusText + “).”;
}
message += “\n”;
alert(message);
}

 

About

I am a passionate web developer.

Tagged with: ,
Posted in ajax
One comment on “Jquery ajax ready states

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>