Tip and Tricks: ASP.NET MVC, jQuery Ajax and Each() Function - Display Message after Iteration is Complete

Working with client-side technologies like JavaScript and Ajax can sometimes be a pain in the butt. One practical example is if you’d like to display a message to end users or do something else after all Ajax calls within the loop are completed. In this post I’m going to show how to make it work.

Suppose that we have this JavaScript block below that iterates the table row to get the item ID stored in an input element and then call an action method from the controller through Ajax by passing the itemID as the parameter:

  1. var calls = [];  
  2. $("#OrderList > tbody > tr").each(function () {  
  3. var itemID = $(this).find("td:eq(0) > input").val()  
  4. var req = $.ajax({  
  5. type: "POST",  
  6. url: "@(Url.Action("AddOrder","Customer"))",  
  7. data: { ItemID: itemID },  
  8. success: function (data) {  
  9. //do something with the return data here  
  10. },  
  11. error: function (error) {  
  12. //log error  
  13. }  
  14. });  
  15. calls.push(req);  
  16. });   
Now if you want to display a popup message to end users after all the items are saved to the database then you can simply do something like this after the item iteration: 
  1. $.when.apply($,calls).then(function(){  
  2. $("#divMessage > p").html("Items Saved!");  
  3. $("#divMessage").dialog({  
  4. modal: true,  
  5. width: 400,  
  6. height: 280,  
  7. buttons: {  
  8. Ok: function () {  
  9. $(this).dialog("close");  
  10. window.location.href = '@Url.Action("OrderList","Customer")';  
  11. }  
  12. }  
  13. });  
  14. });  

The code above uses the jQuery when method. This method provides a way to execute callback functions based on one or more deferred objects that represent asynchronous events. If you noticed on the first block of code it uses an array to store the async objects created using this line “calls.push(req)” and then pass the array to the $.when method. You also noticed that the apply method is used. This is because we need to pass in multiple objects in $.when method, the apply is used to convert the array into parameter list.

That’s it! I hope someone find this post useful!