views:

26

answers:

1

Hi, 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);
}
A: 

Your for loop 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.

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();

            var str;
            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);
        }
    );

}

// On page load fetch 4 times and make bar
for (i = 0; i < 4; i++){
            fetchData();
}
patrick dw
So what can i do in this situation?
bah
Updated my answer. Place the relevant code for the request in the callback.
patrick dw
By the way, is there a reason why you're making what appears to be the same request four times in a row? Just curious.
patrick dw
Now it works as it should, thank you!EDIT: php script I'm requesting generates random data, so I do this 4 times.
bah
You're welcome. :)
patrick dw