0

I am making Ajax call for getting data, I am getting 4 rows and those I am using to send an email via toSendEmail() method.. I need to use for loop for Ajax call because my ID is stored in Array (I am using Id to create URL of Ajax)..Here is code for that:

function getData() {
    console.log("Total Element:"+someIds.length); // 4 data

    for (var i=0; i< someIds.length;i++) {  
        $.ajax({
          url: '/SomeURL/' someIds[i];    
// Basic Ajax Coding (type, cache etc......)

            success: function (result1) {
                for(var i=0; i<result1.length; i++) {
                    // Storing data in Predefined arrays.. 
                }
            },
            error: function (error) {
                alert("Errror while.....");
            }
        }).done(function() {
            if(SomeData.length!=0) {
                toSendEmail();
            };
        });    

    }
}

My ajax call is working fine I am getting data as expected.. My problem is Email is getting sent 4 times. I want Email function should call only once. What I need to make changes in my code??

Thank You

2 Answers2

2

Right now, you're calling your toSendEmail function inside the done() method for every Ajax call, which means it'll run on every Ajax completion. You only want it to run once, after all Ajax are done, so use jquery's when(). More info: Wait until all jQuery Ajax requests are done?

Hayden Schiff
  • 3,280
  • 19
  • 41
  • I want Ajax call to be run in for loop, because I am sending ID in URL by array – Pruthviraj Mohite Sep 25 '17 at 23:36
  • I realized that now (I was thinking your Ajax calls were what caused the email to be sent) and have corrected my answer ; sorry about that – Hayden Schiff Sep 25 '17 at 23:38
  • I already have array in success function for collecting data and store in different array... but the for loop I shown in my post that pass the ID from array in URL.. I will edit post for you.. – Pruthviraj Mohite Sep 25 '17 at 23:40
  • Right, but you're calling toSendEmail() in the done() function for every single one of your multiple Ajax calls. Instead, you should only run that code when the every Ajax call has completed, which you can do with jquery.when. – Hayden Schiff Sep 25 '17 at 23:42
2

Get all the lines first, then when the ajax calls have all completed, send the email

function getData() {
  var promises = [], lines = [];

  for (var i = 0; i < someIds.length; i++) {
    var xhr = $.ajax({
      success: function(result1) {
        for (var j = 0; j < result1.length; j++) {
          lines.push(whatever);
        }
      },
      error: function(error) {
        alert("Errror while.....");
      }
    });

    promises.push(xhr);
  }

  $.when.apply($, promises).done(toSendEmail); // all done
}
adeneo
  • 312,895
  • 29
  • 395
  • 388