Krishna Krishna - 5 months ago 12
Ajax Question

How to call ajax functions in sequence?

I want ajax functions to execute one after another without

asynch: false
. Because
asynch : false
puts browser in a hang mode.
My code is like this
I have 5 checkboxes
ch1, ch2, ch3, ch4, ch5
each with a value as function name. User can select any number of check boxes but the ajax function associated with checkbox values should execute one after another only.
Lets user selects
ch1, ch5, ch3
so functions should execute like

f1() -> f3() - >f5();


functions are like this

function f1(){
$.ajax({

});
}
function f2(){
$.ajax({

});
}
function f3(){
$.ajax({

});
}
.
.
so on


I tried calling successive function in ajax success method but this creates a problem if user selects random checkboxes.

Answer

I had a similar situation like this.
Solution
First make an array of selected checkboxes with values as array elements. Then make a function that check for that value and call its corresponding function.

 function callRequired(array) {
            var required = array[0];
            if (required === "f1") {
                f1(array);
            }
            if (required === "f2") {
                f2(array);
            }
            if (required === "f3") {
                f3(array);
            }
            if (required === "f4") {
                f4(array);
            }
            if (required === "f5") {
                f5(array);
            }
        }

Then simply simply remove that element and call callRequired(array) by removing the previous string as followes

function f1(array) {
        jQuery.ajax({
            url: "some/url",
            success: function (response) {
                array.splice(0, 1);
                callRequired(array);
            }
        });
    }
function f2(array) {
        jQuery.ajax({
            url: "some/url",
            success: function (response) {
                array.splice(0, 1);
                callRequired(array);
            }
        });
    }
function f3(array) {
        jQuery.ajax({
            url: "some/url",
            success: function (response) {
                array.splice(0, 1);
                callRequired(array);
            }
        });
    }
function f4(array) {
        jQuery.ajax({
            url: "some/url",
            success: function (response) {
                array.splice(0, 1);
                callRequired(array);
            }
        });
    }
function f5(array) {
        jQuery.ajax({
            url: "some/url",
            success: function (response) {
                array.splice(0, 1);
                callRequired(array);
            }
        });
    }

Hope this works. Thanks