Im processiing a json response


link_cart.onclick = function(){

In the first line, the product_id value is correct, the json is a list of products, but it doesn't behave strangely,

But the second reference in the onclick handler, displays a value of 22, which is the product_id of the last of 22 products...

I feel im missing a small, key piece of info here...


I solved it myself!

Found this article http://www.howtocreate.co.uk/referencedvariables.html

Seems that the problem is the onclick handler is executed in the context of my for() loop being completed... so you need to pass those variables out of the loop to another function, which returns a function which uses your variables, but preserves them...

//function which preserves vars
function preserver_addtocart(pid){
     return function(){

//loop loooking through my json response
for(var i in bits){
     link_cart.onclick = preserver_addtocart(bits[i].product_id);