I am submitted a getJSON request to a controller in my application, this controller is returning valid JSON with 2 "applications." I know this for a fact as if I move the alert statement to within jQuery's each function it will give me the expected result.
I am attempting to store this data within a multidimensional array to later be used with extJS' Menu Control.
Code:
Ext.onReady(function() {
var applicationList = [];
jQuery.getJSON('index.php/applications', function(data) {
jQuery.each(data.applications, function (i, app) {
applicationList[i] = [];
applicationList[i]['text'] = app['title'];
applicationList[i]['id'] = app['slug'];
});
});
alert(applicationList[0]['text']);
var applicationMenu = Ext.menu.Menu({
items: applicationList
});
});
JSON Response:
{"applications":[{"slug":"test","title":"Test"},{"slug":"hardware","title":"Hardware"}]}
Expected Result:
Test
Actual Result (from Firebug):
applicationList[0] is undefined
If I replace the alert()
above, with the following code I get one alert window with the text "remove":
for (p in applicationList) {
alert(p);
}
Now, my thinking is that the JSON request isn't completing in-time for the alert()
so I'll use a named callback function to ensure the request has completed:
var data;
jQuery.getJSON('index.php/applications', get_applications(data));
function get_applications(data) {
jQuery.each(data.applications, function (i, app) {
applicationList[i] = [];
applicationList[i]['text'] = app['title'];
applicationList[i]['id'] = app['slug'];
});
};
But now Firebug is telling me that data is undefined
...
I feel like I am almost there, but I've been almost there for the past hour and I feel as if I am just polluting the source now in trying to get it to work.