1

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.

1
  • 1
    This is a scope issue with tid; (you have it as a global) and not a "timing" or other issue; i.e. put it inside the scope of the callback function success Commented Apr 3, 2017 at 18:24

1 Answer 1

2

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)
        }
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

even add var tid = ... to keep out of that global scope BUT that does make the assumption it is NOT needed outside this scope however.

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.