0

I did some reading about 'asynchronise ajax json calls' and I also watched some tutorials on youtube. After that I came up with the code below to return the response of the getJSON call in a global variable called fieldList. But the objects in my var fieldList stay empty. I think it is due to the asynchronise call being completed, after filling var fieldList. But I'm lost on how to solve this at the moment. So can anyone help me with my code?

My .js file:

  var fieldList = $("div.slctField");  

    $("#slctTable").change(function()
    {
        $.getJSON("dropdown_code/get_fields.php?table=" + $(this).val(), success = function(data)
        {
            var options = "";
        for(var i = 0; i < data.length; i++)
            {
                options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
            }
        $("#slctField").html("");
        $("#slctField").append(options);
        $("#slctField").change();
    });    
    });

console.log(fieldList);

This is what I'm getting back at the moment(an empty object): enter image description here

I checked what's in my select list now and first i tryed to get the options out of the list and that worked. I got the following output:

enter image description here

And when i check what was in the options i got the values like this:

enter image description here

But when i tryed to get all the values out of the dropdown with this code:

var values = $("select#slctAttribute option").map(function() {return $(this).val();}).get(); 

console.log(values);

I got this back in my console:

enter image description here

So it's still empty but I don't know why?

L. Grunn
  • 175
  • 2
  • 15
  • Putting `fieldList = $("div.slctField"); ` at the end of the `getJSON` function may help if what I'm guessing is what you want. – Chintan May 21 '16 at 14:15
  • I added `fieldList = $("div.slctField");` right after `$("#slctField").change();` but my global ` var $fieldList` still had no objects in it. – L. Grunn May 21 '16 at 14:22
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – JJJ May 21 '16 at 14:22
  • Yeah Juhana i did read up on that question. But I'm still not getting what I'm doing wrong here? – L. Grunn May 21 '16 at 14:24
  • Yeah it is. Because if someone could tell me what's wrong with my code, I could understand what i did wrong. – L. Grunn May 21 '16 at 14:29
  • @L.Grunn No, `console.log` it right there, after `$("#slctField").change();` not outside the function. – Chintan May 21 '16 at 14:35
  • Yeah that works. Now i am getting back the objects. But now the global `var fieldList` is undefined. – L. Grunn May 21 '16 at 14:40
  • @L.Grunn Too many comments, added an answer. Do read the answers to the question linked in the comments above. – Chintan May 21 '16 at 15:42

1 Answers1

2

Consider the code that you have written.

On $("#slctTable").change(), the $.getJSON is executed.

$.getJSON is an asynchronous function which means that the ajax request is sent and the success callback function that you have specified will be executed only after the ajax completes successfully.

    var fieldList = $("div.slctField");  

    $("#slctTable").change(function()
    {
        $.getJSON("dropdown_code/get_fields.php?table=" + $(this).val(), success = function(data)
        {
            var options = "";
        for(var i = 0; i < data.length; i++)
            {
                options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
            }
        $("#slctField").html("");
        $("#slctField").append(options);
        $("#slctField").change();
    });    
    });

console.log(fieldList);

This means that the statements after $.getJSON will continue executing. Thus, when you reach console.log(fieldList);, the ajax may not have completed. So the content of $("#slctField") may not have been set.

If you console.log inside the success callback, console.log will report the value properly because it is executed only after the ajax request is successful.

The following will show the value properly.

    var fieldList = $("div.slctField");  

    $("#slctTable").change(function()
    {
        $.getJSON("dropdown_code/get_fields.php?table=" + $(this).val(), success = function(data)
        {
            var options = "";
        for(var i = 0; i < data.length; i++)
            {
                options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
            }
        $("#slctField").html("");
        $("#slctField").append(options);
        $("#slctField").change();
        console.log(fieldList);
    });    
    });

EDIT: Consider the following demo.

I have used an ajax request to load some results from Wikipedia and put it in your dropdown as options. Don't bother about the URL.

Click on the getOptions button. Compare the contrast values of console.log 1 - outside the success callback and console.log 2 - inside and at the end of the success callback.

$(document).ready(function() {

  var fieldList = $("#slctField");

  $("#selectButton").click(function() {
    var query_url = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max";
    var search_txt = "ball";
    query_url += "&gsrsearch=" + search_txt;
    query_url += "&callback=?"

    $.getJSON(query_url, function(json) {
      var options = "";
      var data = json["query"]["pages"];
      //console.log(data);
      $.each(data, function(i, v) {
        //console.log("console.log result: " + data["extract"]);
        options += "<option value='" + v["extract"] + "'>" + v["extract"] + "</option>";
      });

      $("#slctField").html("");
      $("#slctField").append(options);
      console.log("Console.log 1: Fieldlist " + fieldList.children().first().val());
    });
  });
  console.log("Console.log 2: Fieldlist " + fieldList.children().first().val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div>
  <select id="slctField" class="slctField">
  </select>
  <input type="button" value="Get Options" id="selectButton">
</div>
Chintan
  • 773
  • 9
  • 18