Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for JSON data to be parsed

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.

like image 486
Benedikt Avatar asked Dec 02 '22 07:12

Benedikt


2 Answers

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
  });
}
like image 146
Matthew Flaschen Avatar answered Dec 04 '22 00:12

Matthew Flaschen


You could try doing a synchronous request, like this:

 $.ajax({
      type: "GET",
      url: "www.foo.com",
      data: data
      async: false,
      dataType: "json"
  });
like image 44
cloudhead Avatar answered Dec 03 '22 23:12

cloudhead