Reputation: 418
So I am having troubles understanding passing JSON data.
function getFooterContent(){
//ajax call to get json file
$.getJSON("scripts/pageData/footer/footerData.json", function(jsonData){
console.log(jsonData);
return jsonData;
}).fail(function(){
console.log("fail");
return -1;
});
//Return the json file
}
function someFunction(){
var someContent = new Object();
someContent = getFooterContent();
console.log(someContent);
}
So right now I'm calling a JSON file. And when I console.log(jsonData) I get an Object, which is what I want. So then I can someContent.theContent. Though when the jsonData is returned to the someFunction and I console.log(someContent) I get undefined. I don't understand, I thought it would be an object like it is in the getJSON function.
Upvotes: 0
Views: 200
Reputation: 42450
This is beacause $.getJSON
is asynchronous. So, when getFooterContent()
returns, at that point the JSON data hasn't been retrieved yet, hence the undefined
.
What you should instead do is have getFooterContent()
return a promise object.
function getFooterContent() {
var promise = $.getJSON("url");
return promise;
}
function someFunction() {
var promise = getFooterContent();
var outsideCopy;
promise
.done(function(data) {
outsideCopy = data;
console.log(outsideCopy);
})
.fail(function(e) {
console.log('Error');
console.log(e);
});
}
The above example can be shortened by removing the variable declarations. I left them in so the code is easier to understand
Upvotes: 2
Reputation: 21795
getJSON is called asynchronously, so you are not getting what you expect.
Let me explain:
function getFooterContent(){
//ajax call to get json file
$.getJSON("scripts/pageData/footer/footerData.json",
function(jsonData){ // This function is executed when request is ready and server responds with OK
console.log(jsonData);
return jsonData;
}).
fail(function(){ // This when servers responds with error
console.log("fail");
return -1;
});
//Return the json file
// You are returning undefined actually
}
function someFunction(){
var someContent = new Object();
someContent = getFooterContent();
console.log(someContent);
}
You need:
function someFunction(){
var someContent = new Object();
getFooterContent(function(someContent){
// someContent is passed by getFooterContent
console.log(someContent);
});
}
Here is how you pass arguments to a callback JavaScript: Passing parameters to a callback function
For your function it will be:
function getFooterContent(done, fail){
$.getJSON("scripts/pageData/footer/footerData.json",
function(jsonData){ // This function is executed when request is ready and server responds with OK
// console.log(jsonData);
// return jsonData;
done.call(null, jsonData); // or done.apply()
}).
fail(function(){ // This when servers responds with error
// console.log("fail");
// return -1;
fail.call(); // or fail.apply()
});
}
Upvotes: 4