0

I have the following code:

function bestMove() {
  var url = "http://www.api.com"; // supposed to send {"location":4} in json format.
  $.getJSON(url, function(data) {
    console.log(data);
    return data;
  });
}

$(function() {

  console.log(bestMove())
  //driver code here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

the function console.log(data); in bestMove() logs {location:4}(which is what I want) but the one outside the function logs undefined. However, the variable data is returned so why would the values be different?

Also, when I use JSON.parse(data), Chrome returns this error:

Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at Object.success (tictactoe:5)
    at u (jquery-3.3.1.min.js:2)
    at Object.fireWith [as resolveWith] (jquery-3.3.1.min.js:2)
    at k (jquery-3.3.1.min.js:2)
    at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2)
Luke
  • 565
  • 5
  • 19
  • 3
    Duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Tyler Roper Aug 27 '18 at 02:34

2 Answers2

2

You should be able to make the following updates to your code to achieve what you're after:

function bestMove() {
  var url = "http://www.api.com"; // supposed to send {"location":4} in json format.

  // Return the result of $.getJSON 
  return $.getJSON(url, function(data) { 
    console.log(data);
    return data;
  });
}

$(function() {

  // Add a then handler after bestMove() is called. The function
  // handler will give you access to driver data returned from to
  // ajax response
  bestMove().then(function(driver) {

    //driver code here
    console.log(driver)
  })
});
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
  • 1
    Sorry if the answer is kind of obvious but I still can't parse the data with `JSON.parse(driver)`. Thanks for the fast reply thou – Luke Aug 27 '18 at 02:41
  • 1
    @LuketheGeek `{location:4}` is a JavaScript object, not JSON. `$.getJSON` is already parsing the result for you. You're trying to parse something that's already been parsed :) – Tyler Roper Aug 27 '18 at 02:43
  • @TylerRoper But how can I get the value of `location` then? – Luke Aug 27 '18 at 02:46
  • 1
    @LuketheGeek It's an object, so you can do either `objectName.propertyName`, or `objectName["propertyName"]`. If your object is named `data` and the property you want is `location`, then you'd do `data.location`. – Tyler Roper Aug 27 '18 at 02:47
  • It's generally considered bad practice to simply give the code that solves someone's problem. See https://meta.stackoverflow.com/q/334822/6727154 – michaelitoh Aug 27 '18 at 02:48
  • @MichaelMontero This answer gives more than just code. An explanation is commented within the code itself. – Tyler Roper Aug 27 '18 at 02:48
1

You need to update the code like this

function bestMove(callback) {
 var url = "http://www.api.com"; // supposed to send {"location":4} in json format.
  $.getJSON(url, function(data) {

    return callback(null, data);
 });
}

$(function() {

 bestMove(function(err, data){
   console.log(data);
 });
});

Here I am using Error Callback first. The data you get in callback function is Javascript Object which is already parsed and hence it is not necessary to parse the object. You can directly use it with "." operator or "[]" to access the property.

Saurabh Ghewari
  • 689
  • 3
  • 8
  • 3
    It's generally considered bad practice to simply give the code that solves someone's problem. See https://meta.stackoverflow.com/q/334822/6727154 – michaelitoh Aug 27 '18 at 02:43
  • Noted. Will consider hence forth. – Saurabh Ghewari Aug 27 '18 at 02:46
  • Let me know the reason why it has been downvoted. Hence forth i will be aware of this. – Saurabh Ghewari Aug 27 '18 at 02:49
  • I've downvoted your answer because you gave no explanation - it's code only, as has been pointed out. It's great that moving forward you'll be more aware, but if you'd like to have the downvote removed for *this* answer, then you should edit it to provide some more detail. (**EDIT:** You've provided a bit of detail so I'll now remove the downvote.) – Tyler Roper Aug 27 '18 at 02:50
  • Ohhk. I don`t have problem with downvote, I just want to know the reason. I will be aware of this. Thank you very much. – Saurabh Ghewari Aug 27 '18 at 02:51