Populating an array via ajax request

I need to collect some data from a database via AJAX and put it into an array. Unfortunately, for some reason I can't archive this.

AJAX sends data to retrieve specific data. This data looks like this:

[{"comment_id":154,"comment_text":"Moduleboeken PHP","date_updated":"2015-06-01 10:34:47"},{"comment_id":155,"comment_text":"Moduleboeken JAVA","date_updated":"2015-06-01 10:34:54"}]
[{"comment_id":149,"comment_text":"Werksfeer","date_updated":"2015-06-01 10:33:57"}]
[{"comment_id":152,"comment_text":"Begeleiding Elleke Jagersma","date_updated":"2015-06-01 10:34:27"}]
[{"comment_id":260,"comment_text":"Studievoortgang JAVA","date_updated":"2015-06-01 13:01:15"}]
[{"comment_id":153,"comment_text":"Faciliteiten","date_updated":"2015-06-01 10:34:39"}]

      

A function to collect this data:

function sendRetrieveAjax(url, data) {
    return new Promise(function(resolve, reject) {
        $.ajax({
            url: url, type: 'post', data: data,                
            success: function(data) {
                resolve(data);
            },
            error: function(request, status, error) {
                reject([{request: request, status: status, error: error}]);
            }
        });
    });
}

      

The main code runs through 5 DOM elements, collects the ID from them and uses it in the AJAX send and receive function. If successful, it puts it into an array.

var elements = $('.note_block');
var dataCollection = new Array();

for(i = 0; i < elements.length; i++) {
    var element = $(elements[i]);
    var data = {
        commenttype_id  :   element.children('#commenttype_id').val(),
        week_id         :   $('#week_id').val()
    }

    sendRetrieveAjax('../functions/getcomments.php', data).then(function(data) {
        console.log(data);
        dataCollection[i] = data;
    });
}
console.log(dataCollection);

      

It's a little annoyingly blank, and the console displays the correct data.

Can someone enlighten me?

+3


source to share


2 answers


You have two problems.

  • You need to associate a value i

    withsendRetrieveAjax

  • You need to print the value dataCollection

    after filling it in (note the use of a promise)

To solve the first problem you need to use IIFE ( Immediate Call Function Expression)



for(i = 0; i < elements.length; i++) {
    var element = $(elements[i]);
    var data = {
        commenttype_id  :   element.children('#commenttype_id').val(),
        week_id         :   $('#week_id').val()
    }

    (function(_i) {
        sendRetrieveAjax('../functions/getcomments.php', data).then(function(data) {
            console.log(data);
            dataCollection[_i] = data;
        });
    })(i);
}

      

And to solve the second problem, you can use an array or promises to store the whole promises request in it and execute them both sequentially and in parallel

var requests = []
;

for(i = 0; i < elements.length; i++) {
    var element = $(elements[i]);
    var data = {
        commenttype_id  :   element.children('#commenttype_id').val(),
        week_id         :   $('#week_id').val()
    }

    // No need to store the URL, just store the data
    requests.push(data);
}

requests = requests.map(function(data) {
    return sendRetrieveAjax('../functions/getcomments.php', data);
});

Promise.all(requests).done(function(responses) {
    console.log(responses);
    dataCollection = responses;
}, function(err) {
});

      

0


source


You need to match every single answer to fix the array index. The most optimal solution in this case would be to use $.when

to provide an array of promises and get a centralized response object with an ordered response of data objects.

I also simplified sendRetrieveAjax

how the $.ajax

promise object already returns:

function sendRetrieveAjax(url, data) {
    return $.ajax({
        url: url,
        type: 'post',
        data: data
    });
}

var promises = $('.note_block').map(function(i) {
    return sendRetrieveAjax('../functions/getcomments.php', {
        commenttype_id: $(this).children('.commenttype_id').val(),
        week_id: $('#week_id').val()
    });
}).get();

$.when.apply(null, promises).then(function() {
    var dataCollection = $.map(arguments, function(data) {
        return data[0];
    });
    console.log('Data Collection', dataCollection);
});

      



Another thing, don't duplicate IDs, use classes instead .commenttype_id

.

Here's a demo: http://plnkr.co/edit/r9NnlxIQjUhNvTYwfLy7?p=preview

0


source







All Articles