0

I call ajax in loop then use the result of those ajax calls, then make another call.As u can see below, in my case I solved it with setTimeout which is an ugly solution.

function get_something(some_arr) {
  $.each(some_arr, function(i, obj) {
    //call in loop
    $.ajax({
      url: "example.com",
      complete: function(data) {
        json = data
      },
      error: function(data) {
        console(data);
      },
    });
  });

  setTimeout(function() {
    $.ajax({
      type: 'POST',
      url: 'example.com/anothe_endpoint',
      data: {
        data: json
      },
      async: false,
      success: function(data, status) {

      }
    });
  }, 5000);

}

How do I execute my second ajax after the ajax in loops in done? I tried to add async to false but without timeout it still failed.

Cody Jonas
  • 151
  • 6
  • This is a mess, and will cause you no end of headache, if it works at all. Refer to this documentation on Deferred Objects / Promise structures. http://tutorials.jenkov.com/jquery/deferred-objects.html – Bosworth99 Mar 23 '16 at 22:43
  • @Bosworth99 I did use deferred which .complete() is a promise. – Cody Jonas Mar 23 '16 at 22:46
  • @Quentin this is not duplicated! – Cody Jonas Mar 23 '16 at 22:47
  • 1
    @CodyJonas — You want to do something after multiple Ajax requests have been made and received responses. That's exactly what the duplicate is about! – Quentin Mar 23 '16 at 22:49
  • 1
    "I did use deferred"... that is not evident in this code. You're just using setTimeout, which could very easily fail. – Bosworth99 Mar 23 '16 at 22:49
  • @Quentin in the answer, it uses $.ajaxStop, how can I use that? why can't you answer this question? and one of the answer suggested async false, but why it doesn't work in my case? – Cody Jonas Mar 23 '16 at 22:55
  • @CodyJonas — Why should anyone answer this question? It's the same as another question that already has **eighteen** answers. Incidentally, the accepted and highest rated answer there says not to use `ajaxStop` (and `async: false` is deprecated and shouldn't be used). – Quentin Mar 23 '16 at 22:58
  • @Quentin assume $.when() helps but I'm using each also, can u helps? – Cody Jonas Mar 23 '16 at 23:04

0 Answers0