0

I'm getting data from a device and placing the result in a web page. When I run this code from within a window.setInterval function I'm able to see the values without any issue

requestURL = "https://api.spark.io/v1/devices/" + deviceID + "/" + getYFunc + "/?access_token=" + accessToken;
$.getJSON(requestURL, function(json) {
  document.getElementById("curYPos").innerHTML = json.result + "°";
  document.getElementById("curYPos").style.fontSize = "18px";
});

When I run the same code within a function and try to return the value I still get value on the page but when I try to read the value from the function, I get an "Undefined":

function getAccelData(aAxis) //This pulls the Accel data down by Axis for use 
{
    requestURL = "https://api.spark.io/v1/devices/" + deviceID + "/" + getXFunc + "/?access_token=" + accessToken;
    $.getJSON(requestURL, function(json) {
      document.getElementById("curXPos").innerHTML = json.result + "°";
      document.getElementById("curXPos").style.fontSize = "18px";
      return json.result;
    });
}

In this example I'm not even passing the parameter in from the function, I just copied the code that I knew worked and then tried to pass the json.result out. I'm sure it's something simple but I have not been able to figure it out. Any help would be greatly appreciated

Barney
  • 2,355
  • 3
  • 22
  • 37
  • Use console.log inside your function to debug. For instance, console.log(json.result); inside function. – The Onin Jun 11 '15 at 20:40
  • 1
    Your function ends before the async call is completed. That's why you get undefined. – Gary Storey Jun 11 '15 at 20:40
  • Thanks Quentin and Nino. I'll look at the response and also go through the other questions. I'm assuming that I just need to wait until the response comes back via a loop? – Timothy Girard Jun 11 '15 at 22:09

0 Answers0