I have a JSON array like:
[
{
"location":"New York",
"company":"XYZ LTD",
"status":"Active"
},
... etc
]
I am using the following function to return this array from a URL:
var getJSON = function(url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('get', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
We use the function like this:
getJSON('http://example.com/json.php', function(data) {
alert('Data was collected successfully.');
},
function(status) {
alert('Something went wrong while retrieving the location data.');
});
Okay so great this works and the 'data was collected. I am quite new to Javascript and I am unsure of how I would store the data that was collected as a a variable in Javascript.
I have tried:
getJSON('http://example.com/json.php', function(data) {
var myData = data;
},
...end
And:
var myData = getJSON('http://example.com/json.php', function(data) {
return data;
},
...end
But at this point, if I do:
console.log(myData);
Then I get undefined. But if I do:
var myData = getJSON('http://example.com/json.php', function(data) {
console.log(data);
},
...end
I get back [Object,Object] and this is my data!.
So how do I get my data out of the successHandler and stored as a variable?