简体   繁体   中英

Multiple Ajax Calls, One Callback

I'm currently developing a web application with CakePHP-Framework. You're able to see a floor plan and you can drag and drop users from one seat to another.

Some background information:

When I open the floor plan, I generate a hidden variable in the source code with all users and their devices listed, for instance:

var users = "user1,user2,user3"

When someone wants to save the positions of the users on the floor plan, they call this method:

function getPositions() {
   $.each(users.split(","), function(i, user) {
       setPosition('#u'+user, 'us');
   });
}

They call the ajax-method "setPosition":

function setPosition(object, type) {
    var dataX = { "positions": [] };

    var position = $(object).offset();
    dataX.positions.push({
        "object"   : object,
        "posx"     : position.left,
        "posy"     : position.top
    });

    $.ajax("/CakePHP/seats/Rooms/Save/" + type,
    {
        type : 'post',
        data : dataX
    });
}

As you can see, this method is called x times (x = number of users on the floor plan). Of course I don't want to tell a user x times that the function was successful.

What I need: One alert which tells the user floor plan saved (or Error )

You can use $.when to execute some logic when a number of AJAX requests have completed. Try this:

var requests = []; // array to store all requests.

function getPositions() {
    $.each(users.split(","), function(i, user) {
        setPosition('#u'+user, 'us');
    });

    $.when.apply($, requests).done(function() {
        console.log('Requests completed...');
    });
}

function setPosition(object, type) {
    var dataX = { "positions": [] };

    var position = $(object).offset();
    dataX.positions.push({
        "object"   : object,
        "posx"     : position.left,
        "posy"     : position.top
    });

    // add the request to the array
    requests.push($.ajax("/CakePHP/seats/Rooms/Save/" + type, {
        type : 'post',
        data : dataX
    }));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM