SivaRajini
SivaRajini

Reputation: 7375

stop executing another before one gets completed in jquery

I am using $.ajax inside the for loop in jquery.

for(var i=0; i < 2; 1++)
{

$.ajax({
url :"/models/getdata"+i
dataType:"json"
success:function(data)
{
}
});

}

before going success function for i=0; i=1 comes and performing the ajax request for this value. i want next iteration need to wait until current one gets completed.

that means one ajax request successfully completed and then it will increment the i value then start the next iteration.

consider another scenario also

function A()
{
$.ajax code

}
/////another operation

same here function A() need to wait until its ajax post get completed. but in my case it goes to next code start executing how can i stop further execution before current function gets completed. like sleep concept in C#

how can i do this ?

Thanks,

Siva

Upvotes: 0

Views: 1096

Answers (4)

Nidhin
Nidhin

Reputation: 11

This method could be the best way to handle this problem.

$.when(*AJAX CALL*)
    .then(function() { // Function to run after ajax is completed
});

Upvotes: 0

Moazzam Khan
Moazzam Khan

Reputation: 3170

By default, all requests are sent asynchronously when we use $.ajax. By asynchronously, I meant, web applications can send data to, and retrieve data from, a server (in the background) without interfering with the display and behavior of the existing page. But you want execution to be stopped until your request is complete so set async to 'false'.

Use this -

$.ajax({
    url :"/models/getdata"+i
    dataType:"json",
    async: false,
    success:function(data)
    {
    }
 });

Upvotes: -1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

A simple generic solution :

var i=0;
(function doOne(){
    $.ajax({
        url :"/models/getdata"+i
        dataType:"json"
        success:function(data){
            if (++i<2) doOne();
        }
    });
})();

For your second case, you may use the deferred returned by $.ajax :

function A() {
   return $.ajax(...)
}

A().done(function(){
   // some code executed after the ajax call finished
});

Upvotes: 3

user2587132
user2587132

Reputation:

set async: false in the ajax call

Upvotes: 0

Related Questions