My first function gets a JSON array object via a jQuery AJAX request. My second function tries to access the object, but is hit with a "jQuery.Deferred exception: Unable to get property '1' of undefined or null reference..." (Note '1' refers to my trying to access oJSON[1].name as shown in the following code.)
Here is my JSON:
[{"name":"Alpha", "numWalks":1},{"name":"Beta","numWalks":2}]
Here is my code: (Note: I have to save the JSON as a .txt file and parse it to JSON because of how my SharePoint site is set up.)
var oJSON;
$("document").ready(function() {
getText().done(getDogs());
});
function getText() {
var deferred = $.Deferred();
$.get("dogWalksJSON.txt", function(returnedText) {
oJSON = JSON.parse(returnedText);
});
deferred.resolve();
return deferred.promise();
}
function getDogs() {
console.log(oJSON[1].name);
}
If I console.log(oJSON[1].name) in the getText() function, it works. But when I try to access that info from the getDogs() function, I get the exception. My guess is that it's trying to access the info before it's ready (if I try to access it from my browser's console, it works), which is why I added the defer/promise.
Anyone have any suggestions to how I can fix this?
Thanks!