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);
            }
        });
    });
}
3
  • that's a great way to do that...I just learned a new lesson, thanks Alnitak
    – Shades88
    Jul 3, 2012 at 12:42
  • @Shades88 yes, it's a lot nicer (IMHO) than using an explicit additional closure
    – Alnitak
    Jul 3, 2012 at 12:45
  • So that's how we use the .each function. Thank you very much.
    – Jian Short
    Jul 4, 2012 at 4:47
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
  • Thanks for the information. I actually have it solved using the way you mentioned about.
    – Jian Short
    Jul 4, 2012 at 4:48
  • really? that's great, glad to help. then how about accepting my answer? ;)
    – Shades88
    Jul 4, 2012 at 7:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.