Search code examples
javascriptjquerycallbackgetjson

getJSON done callback


I have the function bellow called every 5 seconds to get data from the server, which is flask/python. My question is how can I adapt the getjson call to have callback when the data is successfully retrieved.

I know there's .done .fail and so on, but I was wondering if I can keep this structure and just add bellow it, but I don't know the syntax in this particular case, hope this isn't too confusing, thanks for reading, here's the code.

// get data from the server every getDataFromServerInterval milliseconds
var getDataFromServerInterval = 5000;
function getData(){
  // request timesince table entries from server for user...
  $.getJSON($SCRIPT_ROOT + '/_database', {
    action: "getUserTable_timesince",
    username: $('input[name="username"]').val()
  }, function(data) { // do something with the response data
    timesince_dataBuffer = data;
  });
  return false; // prevent get
}
// get data from the server every getDataFromServerInterval milliseconds
setInterval(getData, getDataFromServerInterval);

Solution

  • You could do something like this. Instead of processing the data in getData or using a callback, take advantage of the promise that $.getJSON returns. Have a separate function that is called by the timeout which calls for the data, then processes it. It neatly separates your code out into more managable functions.

    var getDataFromServerInterval = 5000;
    
    function getData() {
      return $.getJSON($SCRIPT_ROOT + '/_database', {
        action: "getUserTable_timesince",
        username: $('input[name="username"]').val()
      }
    }
    
    function wrangleData() {
      getData().then(function (data) {
        console.log(data);
      });
    }
    
    setInterval(wrangleData, getDataFromServerInterval);