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)