My script works very strange, I get all the values, but when I want to check them by alerting them – first one gives “undefined”, and other ones is correct. But if I don’t make any alert all variables shows “undefined”. My code:
var arr = new Array();
function fetchData(){
$.get("post.php",
function(data){
arr.img = $(data).find("img").attr("src");
arr.link = $(data).find("td:last a").attr("href");
arr.title = $(data).find("td:last a:first b u").text();
arr.post = $(data).find("td:last span").text();
}
);
}
// On page load fetch 4 times and make bar
for (i = 0; i < 4; i++){
var str;
fetchData();
alert(arr.img);
alert(arr.link);
alert(arr.title);
alert(arr.post);
str = "<td><tr><td><a href='" + arr.link + "'><img src='" + arr.img + "' width='100' height='100' /></a></td></tr><tr><td><strong>" + arr.title + "</strong> - " + arr.post + "</td></tr></td>";
$("div").append(str);
}
Your
forloop runs before the response is received.The reason why the last 15 times work is that by the time you dismiss the first alert, the response has been received.
Place the alerts in the callback, and you’ll see what I mean.