0

Hoping someone can help. I'm in the process of learning JQuery and I'm stuck trying to return a value from this function.

To troubleshoot I'm logging on the console that the data is pulled through correctly via JSON and it is, it's just the value that's not returning.

Any advice would be much appreciated!

    // Get initial categories
var catstr = $.getJSON("scripts/json-categories.php",displayCategoryData);

 function displayCategoryData(data) {
    catResult = data;
    var str ='';
    for(var i=0; i<data.length;i++) {
       str+= '<option value="' + data[i].id + '">' + data[i].category + '</option>';
    }
    console.log(str);
    return str;
 }

$('#category1').html(catstr);
MKC
  • 186
  • 1
  • 15
  • `getJSON()` is an asynchronous AJAX call. As such, it completes long after your function completes so you can't return a value directly. Read the answers in the question I marked yours a duplicate of for various other solutions. – jfriend00 Aug 17 '14 at 23:27
  • ```.getJSON()``` doesn't return value from your function to ```catstr```. That's the problem. If you want fix it, then call ```$.getJSON()``` without write to catstr. And then replace ```return str``` with ```catstr = str```. – Eugene Obrezkov Aug 17 '14 at 23:28
  • @EugeneObrezkov: He will also have to move the `.html()` call inside the callback. So he may as well just change `return str;` to `$('#category1').html(str);`. – Travesty3 Aug 17 '14 at 23:32
  • @EugeneObrezkov - that's a terrible idea. The calling code will not know when the value is available and it won't be available until some indeterminate time later. The correct answer is to write proper async code. – jfriend00 Aug 17 '14 at 23:32

1 Answers1

1

The problem is that getJSON is asynchronous, so it can't return what you want because, in fact, it will run in the future.

Instead, you must do what you wanted to do with return value in the callback function:

$.getJSON("scripts/json-categories.php", function displayCategoryData(data) {
    catResult = data;
    var str ='';
    for(var i=0; i<data.length;i++) {
       str+= '<option value="' + data[i].id + '">' + data[i].category + '</option>';
    }
    console.log(str);
    $('#category1').html(str);
});
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • @RokoC.Buljan But he is not aware it's asynchronous. Not sure about which `this` you are talking about. – Oriol Aug 17 '14 at 23:24
  • @RokoC.Buljan: The OP is attempting to call `.html(catstr)`. `catstr` is given the return value from `$.getJSON()`. `$.getJSON()` does not return the data returned by the server. That's one issue. The other issue is that he's calling `$(#'category1').html(catstr);` outside of the success callback. Since it's an asynchronous call, it's happening before the server has returned a response anyways. So he's not already using it asnychronously. Not sure what you're talking about. – Travesty3 Aug 17 '14 at 23:30