Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
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:

$( 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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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();
    });
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!