LA_
LA_

Reputation: 20419

How to trigger ajax requests queue start?

I follow the approach given in this answer to create queue of ajax requests. But my queue is created online (depends on user actions), so I have function like below:

sendMessage = function(fieldName, oldValue, newValue) {
  $(document).queue("ajaxRequests", function() {
    // ...
    $.ajax({
      // ...
      success: function(data) {
        $(document).dequeue("ajaxRequests");
      }
    });
  });
  $(document).dequeue("ajaxRequests");
};

So, I'll call this sendMessage function several times. Since I have $(document).dequeue("ajaxRequests"); at the end of this function, looks like it will not work properly - ajax will be started several times.

So, how to trigger function properly first time? Probably I should check queue length? Or, should I use fully manual queue?

Upvotes: 0

Views: 426

Answers (1)

nikoshr
nikoshr

Reputation: 33354

I would use the deferred object http://api.jquery.com/category/deferred-object/

You create a resolved deferred object acting as a queue and pipe your requests at will. For example

var mid=0; var queue=$.Deferred(); queue.resolve();

function sendMessage(msgId) {
        return $.ajax({
            type: "GET",
            url: "/echo/json/",
            data: {delay: 1},
            dataType: "JSON",
            success: function(){
                console.log("Success for " + msgId+ "");
            }
        });
}

function queueMessage() {
    var m=++mid;
    console.log("Queueing "+m)

    queue=queue.pipe( function() {
        return sendMessage(m);
    });
}

queueMessage();
queueMessage();

A Fiddle to play with it http://jsfiddle.net/j6CKj/

Upvotes: 1

Related Questions