views:

486

answers:

3

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.

+2  A: 

You could try doing a synchronous request, like this:

 $.ajax({
      type: "GET",
      url: "www.foo.com",
      data: data
      async: false,
      dataType: "json"
  });
cloudhead
beat me by a few a seconds +1
ichiban
+5  A: 

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
  });
}
Matthew Flaschen
+1 I don't know why people resist callbacks in Javascript so much...
Paolo Bergantino
+1  A: 

Thank you for your answer. I just set the process to synchronous:

$.ajaxSetup({'async': false});

After that, used my code. Working just fine!

More jQuery Ajax options here

Benedikt R.
Thanks for the tip, I needed a quick fix and asynchronous is not going to give me any extra performance in this situation.
Shard