Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX - Do Stuff in Success or Complete callbacks?

Tags:

jquery

I have a quick question about jQuery's AJAX function.

The way I do my ajax calls I do something along the lines of:

$.ajax({
    type: "GET",
    url: "/wordpress/wp-admin/admin-ajax.php",
    dataType: 'html',
    data: ({ action: 'loadHomePage'}),
    beforeSend: function() {
        document.getElementById('loading').style.visibility = 'visible';
    },
    complete: function(){
        FB.Canvas.setAutoGrow(false);
        FB.Canvas.setSize({height:600});
        setTimeout(function(){
            FB.Canvas.setAutoGrow(true);
        }, 100);
    },
    success: function(data){
        data = $.trim(data);
        $('#ajax-content').hide().empty().fadeIn('slow').html(data);
        FB.Canvas.scrollTo(0,0);                
    }
});

The trouble is, in this particular instance, it's a full website inside a facebook iframe that uses ajax for the page navigation, when navigating between pages it seems to fade the content in multiple times so I was wondering what the best practise was here for the fade in part - should it go in the complete part?

I had the resizing stuff originally in complete but having moved it I think it's made a difference but not sure if it's a placebo effect....

If so, do I achieve it by doing the following:

complete: function(data){
    // fade in etc

and secondly, is it ok to do this if complete comes before success in the ordering of the source code or is the order important, e.g. success and then complete?

like image 220
martincarlin87 Avatar asked Dec 12 '25 17:12

martincarlin87


2 Answers

'complete' fires and the end of the request cycle after both 'success' and 'error' (whichever was appropriate for your request) and its timing is independent of where you declare it in the source code.

The complete function does not receive the 'data' parameter, so if your action depends on the data then it won't work there.

like image 115
Joe Steele Avatar answered Dec 17 '25 00:12

Joe Steele


complete executes after either the success or error callback were executed.

So you will get those possible chains

success --> complete

error --> complete

You might want to only process successful calls.

like image 23
nooitaf Avatar answered Dec 17 '25 00:12

nooitaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!