jfet93 jfet93 - 1 year ago 84
Javascript Question

What container is affected by the ajaxComplete

So I have several divs where the AJAX contents are posted on. The ajaxComplete is trigerred on all AJAX completes, but I would like to know which of the containers are loaded with the new AJAX content. I'm using this, but it is not working.

$(document).ajaxComplete(function( event, xhr, settings ) {
// loadedDOM is one of the containers where AJAX result is posted on
var loadedDOM=xhr.responseText.parent();

What's the best way to know which containers are newly loaded with AJAX results.

Answer Source

I have several divs where the AJAX contents are posted on...

Ajax loads something from the server, it doesn't post anything anywhere. The ajaxComplete call won't be specific to any container div because, well, there isn't any.

If you're using the load method, which is a shorthand method that does an ajax call and then puts the result into a given container, the information about what container it puts it in is not propagated to ajaxComplete (at least, not according to the documentation). You'll need to convert those load calls into separate ajax and text/html calls (see the details in the load documentation) and do something of your own to pass along that information, or write your own wrapper for load which uses load's complete handler to pass along that information.

Re your comment:

is there like a general over arching listener that will capture all loads and find out which of the containers were loaded ?

Not that I know of. You could create your own special load function and have it fire a custom event, then handle that custom event at the document level:

Add our own "load with event" function (once):1

jQuery.fn.loadWithEvent = function() {
    var t = this;
    t.load.apply(t, arguments).then(function() {

Add a general handler for that event (once):

$(document).on("ajaxload", function(e) {
    // Here, e.target is the element it was fired on
    console.log("got it on document", e.target);

Using it (as often as needed):


1 If you're using ES2015 (aka "ES6"), the loadWithEvent function can be a bit simpler:

jQuery.fn.loadWithEvent = function(...args) {
    this.load(...args).then(() => {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download