PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 8, 2022

[FIXED] How to tell when multiple functions have completed with jQuery deferred

 September 08, 2022     .when, ajax, deferred, javascript, jquery     No comments   

Issue

I have 3 functions which handle data pulled in from AJAX, they update the page after the ajax function is called.

When the AJAX function is called I show a loader, I want to hide the loader after the AJAX has completed and the functions have completed.

How can I use deferred with when and then in jQuery to test once all 3 function are completed.

Here is my AJAX code, this hides the loader on AJAX success at the moment, ideally this would be after the 3 functions have been completed / were successful.

The 3 functions receive data to process and display on the page, they are not AJAX functions.

function setUpStocking() {
    $.ajax({
        url: url,
        cache: false,
        beforeSend: function(){
            // Show loader
            $('.loader').show();
        },
        success: function(data){

            updateMyList(data.gifts);
            updateRecievedGift(data.recieved);
            updateGiftsOpenedToday(data.opened);

            // Hide loader
            $('.loader').hide();

        }
    });
}

The functions are outside the AJAX function:

function updateMyList(gifts) {
    // Get data, process it and add it to page
}

function updateRecievedGift(recieved) {
    // Get data, process it and add it to page
}

function updateGiftsOpenedToday(opened) {
    // Get data, process it and add it to page
}

Solution

You need to first make each of these functions return the deferred object jQuery gives you when you make an AJAX request. Then you can put those in to an array, and apply that to $.when(). Something like this:

var deferreds = [];
$.ajax({
    url: url,
    cache: false,
    beforeSend: function(){
        // Show loader
        $('.loader').show();
    },
    success: function(data){
        deferreds.push(updateMyList(data.gifts));
        deferreds.push(updateRecievedGift(data.recieved));
        deferreds.push(updateGiftsOpenedToday(data.opened));

        $.when.apply(deferreds).done(function() {
            // Hide loader
            $('.loader').hide();
        });    
    }
});


Answered By - Rory McCrossan
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing