This is a part of a javascript code that is working good. But I want to display the variable options in //Ex2 line:
if(profId==10){
//alert(profId);
$("#div_sel_residentType").show( "slow" );
var selectElm="<label for=\"sel_residentType\">Sélectionniez le Type du Résident:</label><select class=\"form-control\" id=\"sel_residentType\"><option value=\"0\" selected=\"\">Type Résident</option>";
var options ="";
$.get("../api/v1/get/menus/typeresident.json.php", function(dataset, status){
for (var index in dataset){
options = options + "<option value=\""+dataset[index].id+"\">"+dataset[index].description+"</option>";
//console.log(options);
}
console.log(options);//Ex1
});
console.log(options);//Ex2
selectElm = selectElm + options + "</select>";
//console.log(selectElm);
//$("#div_sel_residentType").html(selectElm);
}
I would like to understand why it displays console.log(options);//Ex1 but not console.log(options);//Ex2
Ex2executes immediately after the$.getcall.Ex1executes after the call has received a response.$.getis asynchronous, which means that the function you hand over to it will be called when the response is available. In the meantime your code will already proceed to be executed, coming to //Ex2 where options is still "".