karansabhani karansabhani - 1 month ago 6
Ajax Question

Call function after another completes in a loop

I have a for loop where I am calling three functions. I need the functions to run in sequence only after the previous one has completed.

I have tried to achieve this using callbacks but it doesn't seem to be working.

Here's the code:

for(let i=0;i<boxval.length;i++){
var value=boxval[i];
a(value,function(returnedValue){
b(returnedValue,function(returnedValue){
c(returnedValue,function(returnedValue){
d();
});
});
});


}



function a(val, callback){
$
.ajax({
type : "get",
url : "myservlet",
beforeSend : function() {
$(
'#text1')
.css(
{
"color" : "red"
});
$(
'#text1')
.text(
"Running Graph");
},

data : {
"boxval" : val
},
success : function(
responseText) {
$(
'#text1')
.css(
{
"color" : "green"
});
$(
'#text1')
.text(
responseText);


callback(val);

}
});

}
function b(val, callback){
$
.ajax({
type : "get",
url : "ConnectServlet",
beforeSend : function() {
$(
'#text2')
.css(
{
"color" : "red"
});
$(
'#text2')
.text(
"Copying Files and preparing pSet");
},
data : {
"boxval" : val
},
success : function(
responseText) {
$(
'#text2')
.css(
{
"color" : "green"
});
$(
'#text2')
.text(
responseText);


callback(val);

}

});

}
function c(val, callback){
$
.ajax({
type : "get",
url : "CopyServlet",
beforeSend : function() {
$(
'#text3')
.css(
{
"color" : "red"
});
$(
'#text3')
.text(
"Running Dynamic Diff Graph");
},
data : {
"boxval" : val
},
success : function(
responseText) {
$(
'#text3')
.css(
{
"color" : "green"
});
$(
'#text3')
.text(
responseText);


callback(val);


}
});
}

function d(){
$(
'#summary')
.show();
}


What am I doing wrong and how do I get this to work?

Answer

As many have given you solutions already I wont spare time giving the same solution, I still am sure that the execution will not happen as expected, Since you have callbacks which are assigned values using Index it will break for sure. Reason is when the ajax is success and the callback is executed the the index will be incremented to point to a different number. Now your callbacks will take these values which is wrong.

So the solution to handle this will be simply to pass back the value passed into the ajax call back into the callback

Change the code as below.

for (i = 0; i < boxval.length; i++) {
    a(boxval[i], function (returnedValue) {
        b(returnedValue, function (returnedValue) {
            c(returnedValue);
        });
    });
}

And change your callback() to callback(val) , val is what passed into the ajax function.

So the conclusion is to change the for loop and the callback as suggested above and move the callback(val) inside of the success of ajax.