How to implement an ajax request queue using jQuery
Asked Answered
A

2

3

What is the best way to implement an Ajax request queue using jQuery? Specifically, I want to accomplish the following:

  • A user triggers any number of Ajax requests within a web page, which need to be queued up and submitted sequentially.

  • The web page needs to receive responses from the server and adjust itself accordingly.

  • Finally, if an error occurs (connection lost, server failed to respond, etc.), I want jQuery to invoke a JavaScript function.

I'm struggling with the last requirement in particular, as the error handling mechanism in jQuery's Ajax functions is not very intuitive. Are there any examples/tutorials that could help me with this task?

Thanks!

Abdominous answered 8/4, 2011 at 21:51 Comment(1)
You might like this: erichynds.com/jquery/using-deferreds-in-jqueryFavouritism
F
2

I've made a few buffers like this. Some examples can be found simple task Buffer and deferred item queue.

As for error handling you can always use .ajaxError

Ferula answered 8/4, 2011 at 21:58 Comment(2)
Thanks, these look promising!Abdominous
@Jen if you use node on the server, think about using socket.io or now ;)Ferula
M
1

jQuery ajax has an error attribute where you can attach a function and the method will only fire if an error occurs. See the below example:

jQuery.ajax({
            type: "POST",
            url: "url",
            dataType:"json",
            data:{},
            success:function(data){                    
                alert("Succeed!");
            },
            error:function (xhr, ajaxOptions, thrownError){
                alert(xhr.status);
                alert(thrownError);
            }    
        });

I hope you find this helpful.

Merchandise answered 8/4, 2011 at 21:56 Comment(1)
Thanks! I've tried these error handlers before, but found their behavior quite unpredictable. I would get a success indication even if the connection was lost...Abdominous

© 2022 - 2024 — McMap. All rights reserved.