Is there a way to wait for jQuery's getJSON method?
I want to parse the data, recieved with this function and just return false/true if a specific string is contained. But due to the asynchronous data processing this seems not to be that easy. Here is a code snippet:
contained = false;
$.getJSON(URL, function ( data ) {
$.each( data, function( i, item ) {
if ( item.Info.code == code ) contained = true;
});
});
After thid code, the function, where this code is placed in, returns the 'contained' value, whis is basically false, because getJSON has not finished yet.
The proper solution is not making it synchronous (this is possible but not advisable). It's using a callback appropriately. Async programming takes getting used to, but it's worth it.
Instead of:
function foo()
{
...
contained = false;
$.getJSON(URL, function ( data ) {
$.each( data, function( i, item ) {
if ( item.Info.code == code ) contained = true;
});
});
// Do something with contained
}
do:
function getContained(containedCallback)
{
$.getJSON(URL, function(data)
{
var contained = false;
$.each( data, function( i, item ) {
if ( item.Info.code == code ) contained = true;
});
containedCallback(contained);
}
);
}
function foo()
{
...
getContained(function(contained)
{
// Do something with contained
});
}
You could try doing a synchronous request, like this:
$.ajax({
type: "GET",
url: "www.foo.com",
data: data
async: false,
dataType: "json"
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With