active learner here. I want to retrieve data via an ajax call and then use the returned data inside another function. I've learned that ajax calls are asynchronous so have tried using callbacks to no avail. It looks like calling my main function within my ajax call is the only way to do this? Is this an accurate statement? This post led me to believe that one could simply define the function as a variable, which would then allow you to use the variable as equal to the data returned. This is what I tried in my code snippets below. The console log in my getChoiceControl function is working but I get an 'undefined' for the console log of the variable set to this function. I'm really trying to understand async calls and how to consume data, assuming this issue is related to async behavior. I've read many articles on in, but due to the fact that callbacks also failed when I tried that I'm wondering if there is simply some other gap in my limited knowledge. Thanks in advance!
function createHTML(data){
var tester = getChoiceControls();
console.log(tester);
var arr = data.d.results;
var container = $('.container');
var categoryLinksContainer = $('<div class="wrapTest" />');
for(var i in arr){
var item = arr[i];
var title = item.Title;
categoryLinksContainer.append(
'<div class="test">'+title+'</div>'
);
}
categoryLinksContainer.appendTo(container);
}
function getChoiceControls(){
$.ajax({
url: _spPageContextInfo.siteServerRelativeUrl+"/_api/web/lists/GetByTitle('TestList')/fields?$filter=(Title eq 'TestColumn')",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (data) {
console.log(data);
return data;
},
error: function (error) {
console.log(JSON.stringify(error));
}
});
}