Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding jQuery AJAX events - success and ajaxSuccess

Need some help understanding the difference between the success and ajaxSuccess events documented here.

success is a local event, while ajaxSuccess is a global event. I understand the difference between a local and global variable, but am having some trouble understanding the concept of event scope.

What are some sample scenarios where one would be preferred over the other?

like image 796
Bryan Avatar asked May 24 '12 12:05

Bryan


1 Answers

you can use global events as such:

$.ajaxSuccess(function(){
//do my global thing here
});

as the global event will fire for every ajax call success, not just the one.

but the

success: function(){/* do local here */});

ONLY fires within the local ajax call function as a private object of that.

Note the

$.ajaxComplete(function(){ });

might be what you are after as it fires on the complete - with or without an error.

EDIT: Special note of the local success: in ajaxSetup global: (this is NOT recommended and you should use the $.ajaxSuccess)

$.ajaxSetup({
    success: function() {
       // local within the ajaxSetup
    }
});

Now, why would we use one over the other? Perhaps you need special filtering of the object returned:

$(selector1).ajax({
    success: function(data){
        processMySelector1JSON(data);
    }
});
$(selectorOther).ajax({
    success: function(data){
        processMySelectorOtherJSON(data);
    }
});
$.ajaxSuccess(function(){
  $('#message').text('Ajax Done!').fadeIn(function(){$(this).fadeOut();});
});
like image 124
Mark Schultheiss Avatar answered Oct 05 '22 13:10

Mark Schultheiss