Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript/jQuery: How to run a function after an each() loop has finished?

I have the following. What is basically happening is I’m prefilling all the dropdowns/select options. I then retrieve the data for the current record and select the appropriate value for each dropdown/select option.

$(dropdowns_sql).each(function (key, value) {
    var sql = value.sql;
    var dropdown = value.dropdown;

    $.post(d + '/inc/db.asp', {
        type: value.sql
    }, function (data) {
        json_object = JSON.parse(data);
    }).done(function () {
        $.each(json_object, function (k, v) {
            $('#' + dropdown).append($("<option></option>").attr("value", v[sql]).text(v[sql]));
        });
    });
});
get_record_data();

My question is how I can ensure that get_record_data(); is run after the loop has finished? As you can see I make POST requests within the loop so what I am finding is that sometimes these don’t finish before get_record_data(); is called.

I did try:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$( document ).ajaxStop(function() {
    get_record_data();
});

However since get_record_data(); is doing an AJAX request as well, I am finding it just goes into an infinite loop

function get_record_data() {
    $.post(d + '/inc/db.asp', {
        type: 'get_record',
        id: complex_record_id
    }, function (data) {
...

Any suggestions? I need support for IE11 as well.

Thanks.

>Solution :

Know how many elements are in dropdowns_sql, make a count var and include the get_record_data call within the done function for the last element.

Something like:

var count = dropdowns_sql.length;
$(dropdowns_sql).each(function (key, value) {
    var sql = value.sql;
    var dropdown = value.dropdown;

    $.post(d + '/inc/db.asp', {
        type: value.sql
    }, function (data) {
        json_object = JSON.parse(data);
    }).done(function () {
        $.each(json_object, function (k, v) {
            $('#' + dropdown).append($("<option></option>").attr("value", v[sql]).text(v[sql]));
        });
        if (!--count) get_record_data();
    });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading