zwitterion zwitterion - 3 days ago 6
jQuery Question

javascript - what is the error with this code?

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

Answer

That ajax call is async meaning that value does not exists on Ex2 at that moment. Solution for that is to use deferred object take a look at this page : DOC

Example from link :

Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach a success callback using the .done() method.

Full example from you code :

var options = "";
var defObj = $.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
    }); 

// get something done after ajax respone
defObj.done(function() {
    console.log(options); //Ex2
    selectElm = selectElm + options + "</select>";
});

or you can do it in single line :

$.get(/*...*/).done(/*...*/);
Comments