IgorAlves
IgorAlves

Reputation: 5540

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

Upvotes: -1

Views: 52

Answers (3)

Nikola Loncar
Nikola Loncar

Reputation: 2671

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(/*...*/);

Upvotes: 1

jeffery_the_wind
jeffery_the_wind

Reputation: 18168

console.log(options); //Ex2

This actually executes first. And look how the variable options is defined:

var options = "";

So if you are looking for something to print to the console, it is just white space so nothing will show up.

Upvotes: 0

ruakh
ruakh

Reputation: 183261

$.get(...) initiates an asynchronous call. So execution will continue with the following statement, and only later (once the GET request has completed) will the callback be executed.

So the console.log(options);//Ex2 line is executed before options is populated. So it's equivalent to console.log("").

Upvotes: 1

Related Questions