0

I have a ajax request within an each() loop.

My first issue was that code outside of the each loop was executing prior to the each() loop completing (async).

I resolved this with the approach mentioned here: https://stackoverflow.com/a/17904856/1560199

The each loop now pushes each ajax response Object to the array, and once complete proceeds as required.

The problem I have is that I can't seem to use responseJSON directly on the ajax Object:

$comment_response_array = [];
$.each($message_id_array, function(message_key, message_id){
   $comment_response_array.push($.fn.get_comments(message_id, $last_refresh).responseJSON);
});

The $.fn.get_comments eventually maps through the this ajax request:

$.fn.ajax_request = function($method, $ajax_file, $data) {
    return $.ajax({
        'type': $method,
        'url': '../../ajax/' + $ajax_file + '.php',
        'data': $data,
        'dataType': "json"
    });
};

With this, $comment_response_array returns an array of undefined Objects.

Just looking for some guidance on whether I am taking the correct approach and just missing something simple, or if I need to change my approach any pointers would be appreciated.

Community
  • 1
  • 1
n00bstacker
  • 323
  • 2
  • 6
  • 23
  • 1
    The `return $.ajax` returns a promise, not a response - have a look at this link under **deferred objects**: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323 – freedomn-m Mar 24 '17 at 14:19
  • @freedomn-m Thanks for this. I have changed over to this, but outside the each loop `$comment_response_array = [];` is still empty. I have tried the when() done() approach with the each loop with no success. The problem is I do not want my `$comment_response_array` to be actioned inside the each loop itself, but once the each loop has finished. – n00bstacker Mar 27 '17 at 09:50

0 Answers0