I have found similar questions to what I want to accomplish however I still don’t fully understand what I am doing incorrectly.
I want to return an array from the $.getJSON() Method and pass it into another function and then display the results.
So for example I have function one() with 2 variables such as name and country. These 2 variables are passed into function two() where they will be compared against data returned from an ajax request.
I then store the results as an array. But want to display the results in function one()
function one() {
Var name = “bob”
Var country = “UK”
two(name, country)
// Display the sheetsData array from function two() here
}
function two(name, country){
Var url = “http://spreadsheets.google.com/.......”
$.getJSON(url, {
format: "json",
async: false
}).done(function callback(json) {
var results = json.feed.entry;
// Loop over json object that is returned from the URL
for (var i = 0; i < results.length; i++) {
var gSheetName = results[i].gsx$name.$t;
var gSheetCountry = results[i].gsx$country.$t;
var gSheetPostCode = results[i].gsx$postcode.$t;
var gSheetNumber = results[i].gsx$number.$t;
// If the name and country variables from one() matches with results
// from within GSheets the results will be stored in an array
if(name == gSheetsName && country == gSheetCountry ){
var sheetsData = {
"GSName": gsSheetName,
"GSCountry": gSheetCountry,
"GSPostCode": gSheetPostCode
// etc.
}
}
}
});
}
I tried the following but it obviously doesn't work. I'm guessing because the array sheetsData is within the call back function and not two()?
function one() {
Var name = “bob”
Var country = “UK”
// Display the sheetsData array from function two() here
var fullResults = two(name, country)
console.log(fullResults);
}