L. Grunn
L. Grunn

Reputation: 185

How to make a variable of an Ajax GET request to retrieve JSON data?

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?

Upvotes: 0

Views: 127

Answers (1)

Chintan
Chintan

Reputation: 773

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>

Upvotes: 2

Related Questions