Reputation: 4539
I cannot seem to access the values in the returned data array from a jQuery.getJSON and I cannot understand why. I have this same code working elsewhere in my app, biggest difference being this particular instance returns one row only, as opposed to multiple in the other places.
When I manually execute the script I can see this JSON output:
[{"total_energy":"34011.920000","earliest_install_date":"2012-01-01"}]
When I execute the code below, the data array is empty / undefined. If I change the ".getJSON" to ".get" I can now see the values in data but I still cannot access them. I have tried via data.total_energy
but I get "undefined". Any help is appreciated.
The Javascript code:
jQuery.getJSON(url, function(data) {
console.log("Earliest Date= " + data.earliest_install_date);
console.log("Total Energy= " + data.total_energy);
})
.done(function() {
})
.fail(function(jqxhr, textStatus, error ) {
var sysError = textStatus + ", " + error;
showPopupMsg(errorClass, logoutFlag, "There was an error retrieving the Environmental Savings data.<br/>If the issue persists please contact SMA for support...<br/>Error: " + sysError);
})
.always(function() {
});
The result in the console is:
Earliest Date= undefined
Total Energy= undefined
Upvotes: 1
Views: 62
Reputation: 43
Try this:
jQuery.getJSON(url, {}) .done(function(data) { console.log("Earliest Date= " + data.earliest_install_date); console.log("Total Energy= " + data.total_energy); }) .fail(function(jqxhr, textStatus, error ) { var sysError = textStatus + ", " + error; showPopupMsg(errorClass, logoutFlag, "There was an error retrieving the Environmental Savings data.
If the issue persists please contact SMA for support...
Error: " + sysError); }) .always(function() { });
Upvotes: -1
Reputation: 9789
Your JSON is an array:
[{"total_energy":"34011.920000","earliest_install_date":"2012-01-01"}]
You need to access the first element of the array returned like so:
jQuery.getJSON(url, function(data) {
console.log("Earliest Date= " + data[0].earliest_install_date);
console.log("Total Energy= " + data[0].total_energy);
})
.done(function() {
})
.fail(function(jqxhr, textStatus, error ) {
var sysError = textStatus + ", " + error;
showPopupMsg(errorClass, logoutFlag, "There was an error retrieving the Environmental Savings data.<br/>If the issue persists please contact SMA for support...<br/>Error: " + sysError);
})
.always(function() {
});
Upvotes: 3