0

I have the below nested $.each loop:

$.each(fromStopAr, function(index, value) {
          $.each(toStopAr, function(key, data2) {
              console.log("Checking for match against departure stop:" + value + " destination stop : " + data2);
              getMatchingStops(value, data2);
           });
      });

It is looping through two arrays of origin and destination stop id's and looping callung the getMatchingStops function to find stops that have a matching trip.

it works fine, however as the arrays have the stops listing from closest to furthest away, I would like to break the loop once I get a success from my AJAX call bellow: (A success means that I'm getting a non empty reponse from my php DB call.)

$.ajax({
    url: 'main.php',
    async:true,
    data: {
      action: 'getMatchingStops',
      fromstopid: fromstop,
      tostopid: tostop,
      deptime: deptime,
      aftertime: aftertime,
    },
    dataType: 'json',
    type: 'post',
    success: function(data) {
      $.each(data, function(key, data) {
        console.log("Matching Stops " + data.route_short_name);
      });
      // This is where I want to break the nested loop that is calling this function - return false doesn't work.
      return false;

    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.log("Error: "+ errorThrown);
    }

As you can see I have tried returning false, however this doesn't work.

How can I stop the $.each loops on the first AJAX sucess?

Yonkee
  • 1,781
  • 3
  • 31
  • 56
  • I can tell you, that ajax inside a for loop is in general not a very good practice. Can't you just put these for-loops into the backend? This would make it much easier. Other than that you would set a variable in the first loop (var shouldBreak=false). You set it to true in the inner loop and then break it in the outer if it is true. But read this first here otherwise it won't work with ajax: http://stackoverflow.com/questions/21819905/jquery-ajax-calls-in-for-loop – Fabian Lurz May 03 '15 at 07:23
  • As stated, it is not recommended to have a loop for AJAX requests. Remember that these are asynchronous calls, so it is possible that they will not complete by the order you call them, so if you are going this way you should work on the ajax queue, however it will be better to run the first loop and then send all the data once by ajax and get all relevant results – Lupin May 03 '15 at 07:41
  • @Lupin They are sync, Im using the async:false. However, you are right it isn't a good idea, however, for POC it will do for now. If it work I will pass the arrays to PHP and let it deal with them. – Yonkee May 03 '15 at 07:56

0 Answers0