-1

I don't understand why I can print out console.log(imgs) but I can not print out console.log(imgs[0])

$(function() {
    var imgs = [];
    var dir = "images/";
    var fileextension = ".png";

    $.ajax({
        url: dir,
        success: function (data) {
            $(data).find("a:contains(" + fileextension + ")").each(function () {
                var filename = this.href.replace(window.location.host, "").replace("http://", "");
                imgs.push(dir+filename);
            });
        }
    });

    console.log(imgs);//ok
    console.log(imgs[0]);//undefined
    //$('body').css({'background-image': 'url(images/' + imgs[Math.floor(Math.random() * imgs.length)] + ');'});
});
Tomalak
  • 332,285
  • 67
  • 532
  • 628
Cver
  • 73
  • 11

3 Answers3

1

The ajax method is async, so you need to use a callback function to use the imgs variable after the ajax call. Or you can move your code inside the success function, like this:

$(function() {
    var imgs = [];
    var dir = "images/";
    var fileextension = ".png";
    $.ajax({
        url: dir,
        success: function (data) {
            $(data).find("a:contains(" + fileextension + ")").each(function () {
                var filename = this.href.replace(window.location.host, "").replace("http://", "");
                imgs.push(dir+filename);
            });

            console.log(imgs);//ok
            console.log(imgs[0]);//undefined
            //$('body').css({'background-image': 'url(images/' + imgs[Math.floor(Math.random() * imgs.length)] + ');'});
        }
    }); 
});
1

That's because Ajax is asynchronous and JavaScript is synchronous.

You need to console.log in the success callback function.

Rahul Arora
  • 4,503
  • 1
  • 16
  • 24
0

By default $.ajax run asynchronously. If you add more console logs like in this example:

$(function() {
var imgs = [];
var dir = "images/";
var fileextension = ".png";
console.log('telling jquery to load some data')
$.ajax({
    url: dir,
    success: function (data) {
        console.log('data loaded');
        $(data).find("a:contains(" + fileextension + ")").each(function () {
            var filename = this.href.replace(window.location.host, "").replace("http://", "");
            imgs.push(dir+filename);
        });
        console.log('data parsed');
    }
});

console.log("try to print images", imgs[0]);
//$('body').css({'background-image': 'url(images/' + imgs[Math.floor(Math.random() * imgs.length)] + ');'});
});

You will see that when you tries to print imgs[0] ajax not yet loaded.

Arnial
  • 1,433
  • 1
  • 11
  • 10