0

I am having an each loop in JQuery in which I trigger an ajax request. I want to display one success message after all the ajax calls are done executing.

My code goes below,

$('.container input:checked').each(function() {
  json_data = $(this).parent().parent().find('.case_json').html()
  $.ajax({
    type: "POST",
    url: "/some_action",
    data: { json_data : json_data },
    success: function(data) {
      console.log('saved')
    }
  })
}).promise().done( function(){ $('#import_message').show().addClass('alert alert-success').html('Data imported successfully!') } );

But the problem with the code is my success message is getting displayed way before the ajax calls are done executing.

What am I doing wrong? Or do I need to change the way I implemented?

Sri Harsha Kappala
  • 3,339
  • 26
  • 23
  • 30
  • 1
    as you are using jQuery, look into using `jquery.when()` – Jaromanda X Jul 31 '16 at 04:13
  • My guess is currently as soon as the first request finishes it returns a promise and that executes the success message. – Gary Holiday Jul 31 '16 at 04:13
  • maybe, you need https://github.com/caolan/async – saeta Jul 31 '16 at 04:22
  • The code shown shouldn't run at all: you've got a couple of unmatched closing `})`. – nnnnnn Jul 31 '16 at 05:00
  • @nnnnnn My bad! Fixed the code! I followed the accepted answer here http://stackoverflow.com/questions/6591700/how-to-take-an-action-when-all-ajax-calls-in-each-loop-success But I still feel there must be a better way of doing this! I am not getting the big picture here. – Sri Harsha Kappala Jul 31 '16 at 05:09

2 Answers2

1

You need to combine usage $.map function with $.when, here is how it should look like:

$.when.apply($, $('.container input:checked').map(function() {
  json_data = $(this).parent().parent().find('.case_json').html()
  return $.ajax({
    type: "POST",
    url: "/some_action",
    data: { json_data : json_data },
    success: function(data) {
      console.log('saved')
    }
  })
}))
.done( function(){ 
    $('#import_message').show().addClass('alert alert-success').html('Data imported successfully!') 
} );

Map function would create an array of deffereds, this array is passsed to $.when function, the problem is that it's doesn't support array as argument, but support any number of parameters, so we can use .apply() which take array of promises and pass to function as arguments.

Anton Kononenko
  • 477
  • 3
  • 15
0

I think you want to build an array of promises then use $.when.apply. There is a similar problem here: What is cleanest way to turn Array of JQuery Promises into a JQuery Promise of an Array?.

Community
  • 1
  • 1
willywonka
  • 117
  • 5