JS:
$('.product').each(function(){
$parent = $(this);
$.ajax({
url: $parent.attr('url'),
cache: false,
dataType: 'text',
success: function(data){
$parent.text(data);
}
});
});
For each product I want to load some data, say the price. I know the each function is not suitable for this because each does not wait for the async ajax process to finish.
In my example only the last product was filled with data.
How can I load data for each product on document load? Is there a common technique for this situation? Should the request be made for all products at once or for one by another?
Reason: In your code
$parentis not declared locally and hence becomes a global variable. Because of this, the last iteration of$('.product').each() { .. }overwrites it to be the last$('.product')element in your DOM.Solution: If you change
$parent = $(this);tovar $parent = $(this);, it will likely start working correctly.