0

I have to send some requests from a webpage to the server to register a new user. At the end, when all the request were sent, I reload the page. Problem : if I write this simply :

$.post("first request");
$.post("second request");
$.post("third request");
document.location.href=document.location.href;

The page is reloaded before all the request were sent. What I do right now is :

$.post("$RequestUri.get('UserSetter.setName')",{param:$("#usernamesignup").val()},
            function(data)
            {
                $.post("$RequestUri.get('UserSetter.setCountry')",{param:$("#countrysignup").val()},
                function(data1)
                {                   
                    $.post("$RequestUri.get('UserSetter.addDeliveringCountry')",{param:$("#countrysignup").val()},
                function(data2)
                    {                   
                        document.location.href=document.location.href;
                    });
                });
            });

Horrible, isn't it? And in the future, I will have to add other requests. How can I do this properly? Thanks a lot.

Niko

Hermios
  • 622
  • 1
  • 5
  • 20

1 Answers1

1

Well there's no "clean" way in my oppinion. It's asynchronous call. Anyway, maybe instead of creating anonymous function, give them name and wrap in some kind of "request chain" like this:

function startRequestChain() {
    $.post("$RequestUri.get('UserSetter.setName')",{param:$("#usernamesignup").val()}, function(data){
        firstRequestCallback(data);
    });
}

function firstRequestCallback(data){
    $.post("$RequestUri.get('UserSetter.setCountry')",{param:$("#countrysignup").val()}, function(rdata){
        secondRequestCallback(rdata);
    });
}

function secondRequestCallback(data) {
    $.post("$RequestUri.get('UserSetter.addDeliveringCountry')",{param:$("#countrysignup").val()},function(rdata){
        thirdRequestCallback(rdata)
    });
}

function thirdRequestCallback(data) {
    document.location.href=document.location.href;
}

startRequestChain();

You can read more about callback hell here (even though its for node.js, Ajax's callback hell is similar):

Callback hell in nodejs?

http://callbackhell.com/

Node.js/Async - How to avoid callback hell with async?

Community
  • 1
  • 1
kamil
  • 3,482
  • 1
  • 40
  • 64