So I have a script that gets data from an API I setup. It does this in a loop, but it never repeats because i have a problem with the object it returns.
The script looks like this:
<script>
function loop() {
var data = loadJSON("http://myapi.com/api"); //(not real API url)
console.log(data); //Logging this for debugging
numbers = data.data.split("-");
console.log(numbers); //Again, for debugging
//Setting the split data to each variable I that will use later
a = numbers[0];
b = numbers[1];
c = numbers[2];
d = numbers[3];
e = numbers[4];
//Do stuff with the data and then loop again
}
setInterval(loop, 300);
</script>
So the script works fine until I get to the 'data.data.split("-")' part.
The first 'console.log' outputs this:
wich I recognize as a valid object.
The next 'console.log' doesn't output because I get an error before:
The 'loadJSON' is a function from the library p5.js that I'm using. It outputs an object like it should.
The JSON from the api looks like this, wich I think is valid:
{
"data": "30-50-300-20-90"
}
So I did my reseach before asking this question and I found that undefined means:
var data = 0; //Defined variable
data = 0; //Undefined variable
And I tried defining the variable before the function and writing 'var' before each variable but I still got the same error.
I also found this. It says that the state of the object is not the same as the one that I log. That means that when I log it has some data but when I try to split() it doesn't have the same data.
At least that's what I understand.
So I did:
console.log(JSON.stringify(data));
And I got:
just an empty object.
NOTE: There is a similar question How do I return the response from an asynchronous call?, but my question is different. I know how async works and I don't even have jQuery linked on my html file. This is done with the p5.js library.
If there is any more information you need just comment.