JQuery $ when.apply () .. then () shooting for each completed request

Here's the jQuery method that I created in the ASP.NET MVC Razor view. Desired Functionality:

  • Select textAreas
  • Hide ajax request array
  • Once all ajax requests are complete, show a warning dialog

The code works correctly, except that the "ok" warning dialog box appears several times, once for each request. This suggests that the .then () method is called for each request, rather than waiting for all to complete. What am I doing wrong here?

// Save changed entity notes
function saveChangedNotes() {

  var ajaxReqs = [];
  $('textarea').each(function() {
    ajaxReqs.push($.ajax({
        type: "POST",
        url: "@Url.Action("UpdateCompanyNote", "Company", new {companyId = Html.CompanyIdFromRouteValues()})",
        data: {
          noteId: this.id,
          noteText: $(this).val()
        }
      })
    );

    // When all ajax complete..
    $.when.apply($, ajaxReqs).then(function() {      
      alert('ok');
    }).fail(function() {         
      alert('error');
    });
  });
}

+4
source share
2 answers

$.when.apply . .

+5

$.when.apply .

promise = $.when(promise, anotherPromise).

. -

// Save changed entity notes
function saveChangedNotes() {
    // Start with a resolved promise (undefined does the same thing for $.when!)
    var promise;
    $('textarea').each(function () {
        promise = $.when(promise, $.ajax({
            type: "POST",
            url: "@Url.Action("
            UpdateCompanyNote ", "
            Company ", new {companyId = Html.CompanyIdFromRouteValues()})",
            data: {
                noteId: this.id,
                noteText: $(this).val()
            }
        }));
    });
    // When all ajax complete..
    promise.then(function () {
        alert('ok');
    }).fail(function () {
        alert('error');
    });
}
+1

All Articles