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

203
Views
Javascript loop with ajax call

I've been struggling all afternoon to understand how to make this work, hopefully someone can help. I have a simple requirement to run through a list of checked check boxes, retrieve some data from the server, fill an element with the data expand it. So far I have the following code;

function opentickedrows() {
    $('input[type=checkbox]').each(function () {
        if (this.checked) {
            tid = $(this).attr('name').replace("t_", "");
            $.ajax({
                url: '/transfer_list_details_pull.php?id=' + tid,
                type: 'GET',
                success: function (data) {
                    $('#r' + tid).html(data);
                    $("#r" + tid).show();
                    $("#box" + tid).addClass("row-details-open");
                }
            });
        }
    });
}

The problem that I am having is that the ajax calls all seem to happen so fast that 'tid' isn't being updated in the ajax call. From what I have read I believe I need to wrap this up into a couple of functions with a callback but I just can not get my head around how. I'd be really grateful if someone can set me on the right path.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Ajax calls are asynchronous, so when the success callback is invoked, tid has the value of the last item of the $('input[type=checkbox]').

You could use a closure:

function opentickedrows() {
    $('input[type=checkbox]').each(function () {
        if (this.checked) {
            tid = $(this).attr('name').replace("t_", "");
            (function(tid) {
                $.ajax({
                    url: '/transfer_list_details_pull.php?id=' + tid,
                    type: 'GET',
                    success: function (data) {
                        $('#r' + tid).html(data);
                        $("#r" + tid).show();
                        $("#box" + tid).addClass("row-details-open");
                    }
                });
            })(tid)
        }
    });
}
about 4 years ago · Santiago Trujillo 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!