0

I have a javascript file where I expect to call the same getJSON call over and over again. For example:

$(document).ready(function() {
  $('#validate').click(function() {
    var url;
    url = 'http://myurl';
    $.getJSON(url, function(data) {
      if (data[0].response.status === 'ok') {
        $('#validate_text').html("data validated");
      } else {
        $('#validate_text').html("data Not Valid");
      }
    });
  });
});

This works I would like to refactor this to something like:

$(document).ready(function() {
  $('#validate').click(function() {
    var url;
    url = 'http://myurl';
    data = myjsonfunction(url);
      if (data[0].response.status === 'ok') {
        $('#validate_text').html("DLS / NTS Validated");
      } else {
        $('#validate_text').html("DLS / NTS Not Valid");
      }
  });
});

where myjsonfunction(url) is a standalone function I can pass the URL and it returns the raw getJSON data. I have seen a few examples where you set a already defined variable out side the getJSON block etc. but I can't seem to get any of these to work.

Dan Tappin
  • 2,692
  • 3
  • 37
  • 77
  • Possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call). In short, you can't directly return the value but you can return the promise – Phil Oct 27 '15 at 04:18
  • Hmmm... I need to think about this. I see what you are saying. When I call the getJSON directly my code waits for the response but If I try to call it externally it fails overtime because unless the external function returned a result immediately (it can't) the value of data is always undefined (which is what I was seeing when I tried it. – Dan Tappin Oct 27 '15 at 14:44

1 Answers1

0

Try using .then() , as data is asynchronous , if could be called synchronously before response from myjsonfunction(url)

$(document).ready(function() {
  $('#validate').click(function() {
    var url;
    url = 'http://myurl';
    data = myjsonfunction(url);
    data.then(function(response) {
      if (response[0].response.status === 'ok') {
        $('#validate_text').html("DLS / NTS Validated");
      } else {
        $('#validate_text').html("DLS / NTS Not Valid");
      }
    }, function err(jqxhr, textStatus, errorThrown) {
         console.log(erroThrown)
    })
  });
});
guest271314
  • 1
  • 15
  • 104
  • 177