MarieMarie
MarieMarie

Reputation: 65

How can I run Ajax functions synchronously from Javascript?

I have the following code:

$('#DoButton').click(function (event) {
  event.preventDefault();
  $("input:checked").each(function () {
    var id = $(this).attr("id");
    $("#rdy_msg").text("Starting" + id);
    doAction(id);
  });
});

function doAction(id) {
            var parms = { Id: id };
            $.ajax({
                type: "POST",
                traditional: true,
                url: '/adminTask/doAction',
                async: false,
                data: parms,
                dataType: "json",
                success: function (data) {
                    $("#rdy_msg").text("Completed: " + id);
                },
                error: function () {
                    var cdefg = data;
                }
            });
        }

When the button is clicked it checks the form and for each checked input it calls doAction() which then calls an Ajax function. I would like to make it all synchronous with a 2 second delay between the completion of one call and the running of the next. The delay is to give the user time to see that the last action has completed.

By setting async=false will that really make the ajax function wait?

How can I add a 2 second wait after the Ajax has run and before the next call to doAction?

Upvotes: 0

Views: 4283

Answers (3)

redexp
redexp

Reputation: 5065

Try to do it using recursion

$('#DoButton').click(function (event) {
  event.preventDefault();
  doAction( $("input:checked").toArray().reverse() );
});

function doAction(arr) {
    if( arr.length == 0 ) return;

    var id = arr.pop().id;
    $("#rdy_msg").text("Starting" + id);
    $.ajax({
        type: "POST",
        traditional: true,
        url: '/adminTask/doAction',
        async: false,
        data: { Id: id },
        dataType: "json",
        success: function (data) {
            $("#rdy_msg").text("Completed: " + id);
            setTimeout(function(){ doAction(arr); }, 2000);
        },
        error: function () {
            var cdefg = data;
            $("#rdy_msg").text("Error: " + id);
            setTimeout(function(){ doAction(arr); }, 2000);
        }
    });
}

Upvotes: 1

Starx
Starx

Reputation: 78981

There is option in jQuery to set the ajax function synchronous

$.ajaxSetup({
   async: false
});

To make the function to wait you can use .delay()

Try the solution of this question also.

Upvotes: 2

Troy SK
Troy SK

Reputation: 1289

Use setTimeout for the AJAX call doAction.

Upvotes: -1

Related Questions