0

Hi guys so I am starting to learn how to make Ajax calls and I just ran into something and all the info for a solution is a little confusing, perhaps a little advanced for where I am.

So I successfully ran this ajax call to load in images from a folder and add them to an array. however, what if I wanted to call the array elements outside of the ajax function? for this console log I get a blank array, if I put the console log in the ajax call I get the desired result.

How can I use the array outside of the ajax call or am I missing something here?

$(document).ready(function(){

var folder = "imgs/";
var imgArr = [];
$.ajax({
    url : folder,
    success: function (data) {
        $(data).find("a").attr("href", function (i, val) {

            if( val.match(/\.(jpe?g|png|gif)$/) ) { 

                imgArr.push("<img src='"+ folder + val +"'>");
                console.log("val: " + imgArr);

            } 
        });
    }
});

console.log("val: " + imgArr); // shows nothing

});
Sony ThePony
  • 315
  • 1
  • 2
  • 13
  • 1
    because you ordered a pizza on the phone and as soon as you hang up the phone you try to eat the pizza. That is why there is a call back. The doorbell rings you open the door and eat the pizza. You need to wait for the doorbell to ring so the code needs to be run in the success method. – epascarello Sep 08 '16 at 18:35
  • Hahaha, makes sense. Am I able to use any code outside of the success to check if "the pizza has already been delivered" – Sony ThePony Sep 08 '16 at 18:38
  • your AJAX call is async, meaning the console.log at the end will be called before the code in success. To make it synchronous add async: false as property, like $.ajax({ async: false, url .... and so on. Then you will get the desired result. Although it's not really best practice to do that, as you will block the parallel execution of code – Michael Troger Sep 08 '16 at 19:29

0 Answers0