0

When I try push some element to array and display random element, browser return that array is not define. Where is problem?

var dir = "./images/radovi/";
var ext = ".png";
var slike = [];
$.ajax({
    url: dir,
    success: function (data) {
        $(data).find("a:contains(" + ext + ")").each(function () {
            var ime_slike = this.href.replace(window.location.host, "").replace("http:///", "");
            slike.push(dir + ime_slike + ext);
        });
    }
});
$('<img src="' + slike[Math.floor(Math.random() * slike.length)] + '">').appendTo('#radovi');
2
  • Try slike[Math.floor(Math.random() * (slike.length-1))]
    – SeinopSys
    Sep 18, 2014 at 22:30
  • I tried, again same thing. In console return this error "GET localhost/test/undefined 404 (Not Found)"
    – Memiš
    Sep 18, 2014 at 22:34

1 Answer 1

2

AJAX is Asynchronous. The code that populates your array is being called after the code that uses the array. Move the code that creates the image into the success handler:

var dir = "./images/radovi/";
var ext = ".png";
var slike = [];
$.ajax({
    url: dir,
    success: function (data) {
        $(data).find("a:contains(" + ext + ")").each(function () {
            var ime_slike = this.href.replace(window.location.host, "").replace("http:///", "");
            slike.push(dir + ime_slike + ext);
        });
        if (slike.length) {
            $('<img src="' + slike[Math.floor(Math.random() * slike.length)] + '">').appendTo('#radovi');
        }
    }
});
0

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.