I have this code below, which is supposed to return the result of the call. I need to do this synchronously so that I know everything is good, however it doesn't seem to work. What am I doing wrong?
/* jQuery library:
* http://code.jquery.com/jquery-1.9.1.min.js
*/
function getJSON(url){
var result;
$.getJSON(url, { async: false, success: function(data) {
result = data;
alert(data); // **Edit**: also undefined
}});
alert(result); // undefined
return result;
}
I just insert this code before getJSON:
Original answer: Is it possible to set async:false to $.getJSON call
$.getJSON()
does not supportasync: false
and there is no way to even pass that option to$.getJSON()
(look at the arguments in the jQuery doc).Internally,
$.getJSON()
uses$.ajax()
and if you look at the doc page for$.ajax()
, it tells you right there that if the ajax request is cross domain and it's for JSONP, it does not supportasync: false
.The reason for this is that a cross domain JSON request is implemented with JSONP which by definition a dynamically inserted
<script>
tag which can only be asynchronous. It cannot be synchronous.You will need to code your request to be asynchronous if it is cross domain or use
$.ajax()
directly if it is not cross domain.getJSON
has noasync: false
option. You'd have to useajax
for that.According to the documentation,
getJSON
is equivalent to:...to which you can easily add an
async: false
option (for now, be forewarned that jQuery will be dropping support for that).You don't need to do anything synchronously to "know everything is good", it's perfectly possible (and normal) to handle results (whether "good" or errors) asynchronously.
In the comments on your question, you've written:
JSON-P is not the same as JSON (and
getJSON
doesn't do JSON-P unless you havecallback=?
or similar in the URL), and JSON-P is inherently asynchronous. Unlike a true ajax call viaXMLHttpRequest
, it's impossible to make JSON-P synchronous.$.getJSON
is a shorthand for$.ajax
.You'll notice that there is no option for passing through an async option. The parameter you are attempting to add
async: false
to is actually the data that will be sent to theurl
with the ajax request.Try doing this instead:
Also, your statement
is incorrect. You can 'know everything is good' from the asynchronous callback. Your sample code would do what you are trying to do above exactly if you wrote it like this:
You could even define your callback function separately and pass it to
$.getJSON
, like so: