I have this code below, and I want to return the data in the success function of the ajax call. Of course, if I do async:false and return it directly I get it but I don't want to do that.
If I just run it like it is now, information variable is undefined (if I do async:false, it gets the information, so it isn't the contents of the data that is the issue).
I just don't understand why it isn't working, I googled callback functions and it appears that I am doing it right...
function PUT_updateSystem(id) {
var system= {};
system= getSystemInformation(name, function(data){
var system = data;
return system;});
var information = system.info;
}
// Returns system information
function getSystemInformation(name,callback){
$.ajax({
type:"GET",
url: getUrl(),
cache: false,
dataType: "json",
success: function(data){
callback(data);
}
});
}
EDIT: Changed my code to what I currently have
I am generating a jsTree with this data, and to create the json data for that tree I am doing the above but putting the information variable into an object and iterating over it to create nodes. The issue isn't with the tree, so I won't include that here. I can even take that logic out to test.
So what is happening,
- Page starts loading
- I perform the above
- Information gets put into a javascript object
- I iterate over the javascript object.
- I receive an error "Cannot read property 'length' of undefined"
- As I'm debugging, I see that it skips over system.done. This makes sense because it may not be done.
Is there a way to wait for it to be done?
EDIT: Providing more information
// IN A FILE CALLED loadinfo.js
// Returns system information promise
function getSystemInformation(){
return $.ajax({
type:"GET",
url: getUrl(), // url is defined somewhere else
cache: false,
dataType: "json"
});
}
// IN A FILE CALLED tree.js
// I have other variables from loadinfo.js that are here so they can communicate fine
$.when(getSystemInformation(), $.Deferred(function(deferred) {
$(deferred.resolve);
})).done(function(data) {
mapCache["system"] = data;
console.log("defer DONE!!");
$.each(mapCache["system"], function(index, system) {
var children = doDisplayChildNodes(system.name);
...
...
});
What I'm doing in this $.each is just grabbing data from mapCache["system"] and creating a "jstree" node. I do a child function to do the same thing, because I have child nodes associated with each system. All of this logic worked because it work working fine when I had the ajax call as "async:false" -- so I won't post that.
I receive the Cannot read property 'length' of undefined during the $.each. Which is strange because I have a "Watch" set on mapCache and after everything is loaded, mapCache is filled with the correct values. I am using Google Chrome debugging.