Attach functions to jquery ajax call

David Jones
@david3jones
avatar-davidejones

A lot of the work I’m doing at the moment needs me to come up with JQuery solutions to website problems rather than changing server side code or sometimes even regular html. This is due to the fact that the website code I’m working with is shared with so many other websites that changes need to be considered carefully and used only in certain areas. Anyway this limitation means I need to alter existing javascript or jquery to tweak the functionality or response. This can become very tricky when you don’t have direct access to the javascript being called and I have to attempt to override or work around the javascript already in place. One such site I’ve worked on had a lot of ajax post requests going on for shopping cart functionality. After pulling my hair out for some time i found a little snippet of Jquery that saved me a lot of hassle. I can attach an ajaxComplete event listener to the document and any ajax calls can then call my function on completion meaning i can add new functionality or undo something etc. Its as simple as this

$(document).ajaxComplete(function(e, xhr, settings) {
        //do something on any ajax request completion
});

or of course you can still target a specific element as usual and listen for the completion

$(".ajaxclass").ajaxComplete(function(e, xhr, settings) {
        //do something on this ajax request completion
});

Comments

    Comments are currently closed