jqueryajaxreadystateonreadystatechange

jQuery $.ajax and readyStates


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


Solution

  • $.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.