1
function check_timer(){
    //get product ids
    var product_ids= document.getElementsByClassName("product_id");
    //create for loop
    for(var i=0; i<product_ids.length; i++){
        var product_id= product_ids[i].innerHTML;

        $.ajax({
            //send product id to check
            url: "check_last_timer.php",
            type: "post",
            data: {product_id: product_id},
            success: function(end_time){
                //trying to get product_id here

                //$("#timer"+product_id).html(end_time);
            }
        })

    }

}

I am trying to get my product id within the success function. As you can see I have a for loop that sends product_id e.g, 1,2,3...10 to "check_last_timer.php" each time it runs. Problem is how can I get back 1,2,3...10 within the success function. Each time the for loop runs, I get the last product id which is 10.

2 Answers 2

1

You can't use a loop variable declared outside a closure from within that closure.

As you're using jQuery, use .each:

function check_timer() {
    $('.product_id').each(function() {
        var product_id = this.innerHTML;  // or $(this).html()
        $.ajax({
            //send product id to check
            url: "check_last_timer.php",
            type: "post",
            data: {product_id: product_id},
            success: function(end_time){
                $("#timer" + product_id).html(end_time);
            }
        });
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

that's a great way to do that...I just learned a new lesson, thanks Alnitak
@Shades88 yes, it's a lot nicer (IMHO) than using an explicit additional closure
So that's how we use the .each function. Thank you very much.
0

This is because AJAX call is as name suggests asynchronous. The for loop proceeds queuing up ajax calls, so you will get last id as 10 because for loop is too fast and ajax calls take time to complete.

What you can do is send product_id to request. get it back from server in success then do processing

2 Comments

Thanks for the information. I actually have it solved using the way you mentioned about.
really? that's great, glad to help. then how about accepting my answer? ;)

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.