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.

2
  • 1
    The return $.ajax returns a promise, not a response - have a look at this link under deferred objects: stackoverflow.com/questions/14220321/… Commented Mar 24, 2017 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. Commented Mar 27, 2017 at 9:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.