On this code:
$.each(divList, function(){
var dropdown = '';
$.get("ajax.php",{'some':'params', 'other':'params'},function(msg){
dropdown = msg;
console.log( dropdown );
});
console.log( dropdown );
$(dropdown).appendTo($(this));
});
…the first log shows dropdown variable holds the correct text returned from the ajax, the second one is empty (and the appendTo does nothing).
Is there a way to make this works? Is there some dependency with the browser used ?
$.get()is asynchronous: it returns very quickly, performs its work in the background and signals completion by invoking the callback function you supply.Since your second call to
console.log()and your call toappendTo()are outside the callback, they will run too soon, before$.get()completes anddropdownis set.The usual pattern is to put the call to
appendTo()inside the callback function:EDIT: If you want to access the original
thisreference from your callback function, you can pass it in thecontextoption to $.ajax(), as the code above does.