fsloke
fsloke

Reputation: 1

JQuery Multiple AJAX call

Please refer the code below, I already set both of the ajax as async : false. I found out that when the function calling doUpdate2ndAJAX(), the program start executing $(".search").click(); even though doUpdate2ndAJAX() not yet finish executing.

In short current situation: 1. doUpdate2ndAJAX() execute 2. doUpdate2ndAJAX() not yet finish, start execute $(".search").click() 3. doUpdate2ndAJAX() Finish execute and response back

May I know how can I make it as 1. doUpdate2ndAJAX() execute 2. doUpdate2ndAJAX() Finish execute and response back 3. call $(".search").click();

[ Execute in sequence order ]

Thanks. -fsloke

firstCalled: function() {
             $.ajax({                          
            url: "XXX",
            async: false,
            success: function(response) {

                        doUpdate2ndAJAX();

                        $(".search").click();

                        }
           });
}               

function  doUpdate2ndAJAX(){
              $.ajax({                         
            url: "YYY",
            async: false,
            success: function(response) {
                            // UPDATE SOMETHING
                        }
               });
              return false;
}

Upvotes: 0

Views: 1452

Answers (3)

sandino
sandino

Reputation: 3842

Use Deferred objects, those are objects to manipulate async calls, you can solve :

$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
  .then(myFunc, myFailure);

This way myFunc executes after the 2 ajax calls are made, and myFailure if either one has an error.

You can read more about it in the jquery official documentation:JQuery Deferred Object

Upvotes: 1

Fabrizio D'Ammassa
Fabrizio D'Ammassa

Reputation: 4769

I suggest to use the "complete" callback to invoke the $(".search").click().

You can see the differences between success and complete callbacks here: http://api.jquery.com/jQuery.ajax/

Upvotes: 0

SLaks
SLaks

Reputation: 887275

You should make the AJAX calls asynchronous, and call $(".search").click(); in the success callback for the second request.

Depending on your structure, you may want to add a parameter to doUpdate2ndAJAX which tells it whether to call $(".search").click();.
Alternatively, you can add a callback parameter.

Upvotes: 0

Related Questions