jQuery $.ajax and readyStates

tetris picture tetris · Nov 5, 2010 · Viewed 35k times · Source

How to call the Ajax ready states on the jQuery $.ajax method?

Answer

Nick Craver picture Nick Craver · Nov 5, 2010

$.ajax() returns the XmlHttpRequest object, so if you really want to access it as the state changes, you can do this:

var xhr = $.ajax({ ... });
xhr.onreadystatechange = function() { alert(xhr.readyState); };

But the built-in callbacks should be all you need for most uses, particularly success and complete.

To do things before the request fires, use beforeSend, or more appropriately for most cases, the .ajaxStart() and .ajaxStop() events...for example to show a loading message whenever any ajax activity is going on.