Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $when.apply() .. then() firing for each completed request

Here's a jQuery method I've created in an ASP.NET MVC Razor view. The desired functionality is:

  • Select textAreas
  • Fire off an array of ajax requests
  • Once all ajax requests complete, show alert dialog

The code appears to work correctly, except that the alert 'ok' dialog is displayed multiple times, once for each request. This suggests that the .then() method is being 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');
    });
  });
}

like image 537
Marcus K Avatar asked Mar 21 '23 06:03

Marcus K


1 Answers

You're performing the $.when.apply inside the textarea each loop. Count your closing brackets.

like image 93
Adam Avatar answered Mar 23 '23 19:03

Adam