0

I have a loop where I'm making an ajax post. I want to execute the function "doSomething()" only after my loop (and the ajax posts inside each loop) are complete.

I'm thinking this is called a promise, but I'm just getting into jQuery after doing server side forever...

 selectedRows.each(function(e) {
            var dataforpost = { groupId: selectedGroup.Id, 
            userName: userName, displayName: displayName };

            $.ajax({
                url: '@Url.Action("AddMemberToGroup")',
                type: "POST",
                data: dataforpost,
                success: function(data) {}
            });
        });
        
  // now when that loop is done, do something
  doSomething();

1

2 Answers 2

1

You can use $.when:

$.when(selectedRows.each(function(e) {
  var dataforpost = { groupId: selectedGroup.Id, 
  userName: userName, displayName: displayName };

  $.ajax({
    url: '@Url.Action("AddMemberToGroup")',
    type: "POST",
    data: dataforpost,
    success: function(data) {}
  });
})).then(function() {
  // now when that loop is done, do something
  doSomething();
});

OR you can keep track of the last loop and trigger a done function call:

selectedRows.each(function(i, e) {
  var dataforpost = { groupId: selectedGroup.Id, 
  userName: userName, displayName: displayName };

  $.ajax({
    url: '@Url.Action("AddMemberToGroup")',
    type: "POST",
    data: dataforpost,
    success: function(data) {},
    done: function() {
      if (i == selectedRows.length - 1) {
        // now when that loop is done, do something
        doSomething();
      }
    }
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Sam! I couldn't get the first option to run, but I did get the second one to work with a minor edit. I moved the selectedRows.length check to the success function. I couldn't get done: to execute.
0

Perharps helps:

  selectedRows.each(function(index, elem) {
        var dataforpost = { groupId: selectedGroup.Id, 
        userName: userName, displayName: displayName };

        var jqxhr = $.ajax({
            url: '@Url.Action("AddMemberToGroup")',
            type: "POST",
            data: dataforpost,
            success: function(data) {}
        });
        jqxhr.then(function() {
          console.log( index );
          if ((index+1) >= selectedRows.length){
             console.log('last');
             // now when that loop is done, do something
             doSomething();
          }
        });
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.