jQuery: How to identify which XHR handler ajaxComplete() was fired off for

I have multiple $.get() handlers in my JavaScript. I'd like to be able to run specific code when a handler has successfully finished its request. From jQuery's documentation, it looks like the following is what I'm looking for:

$( document ).ajaxComplete(function() {
  $( ".log" ).text( "Triggered ajaxComplete handler." );

The problem I have here is, this is going to get triggered for every $.get() handler. How can I identify which one it is going off for so I can take the correct steps that are required to update my user interface?


You will get the xhr object and the settings object as an argument to the callback, you can use them to identify the ajax method

$(document).ajaxComplete(function (event, jqxhr, settings) {
    $(".log").text("Triggered ajaxComplete handler.");

But if you want to register a callback for a particular ajax request and you have access to that ajax request's promise object then you can use the .always() callback like

var promise = $.post('/echo/json/', {});//or $.ajax() etc
    //do something

Personally I just wrap all jQuery AJAX methods in my own function. That way I can do all sorts of tracking and caching behaviors without relying on hooks. For example:

function AJAXLoad(method, data, callback) {
    var request = method + (new Date()).toString();
    console.log("Sending request " + request);
    $.ajax(method, { data: data, success: function(msg) {
        console.log("Request " + request + " completed.");

Need Your Help

Who owns /var/log/tor logs? Can`t get tor to start

logging permissions tor

I compiled tor and installed it (on raspbian).

Special characters in XML files - processing with the DOM API

xml dom special-characters

I have a file, which is in XML format (consists just of root start and end tags, and children of the root). The text elements of the children contain the ampersand symbol &. In XML it is not al...