Really hoping someone can point in me in the right direction or tell me what I'm doing wrong. Sorry if my explanation isn't great, be kind!
Currently I'm working on creating a function which runs an ajax call, with a dynamically created URL. The function needs to sit in a centralised single spot (e.g. website.com/global-api.js). Ideally, any of our developers should be able to make a call to the function from within their sites (website.com/mysite.html) with the dataset they're wanting to retrieve as an argument, and then alter it as required (I've included a vague diagram which was created to describe the requirement – might not be useful).
global-api.js
function globalApi(value){
var setApiProp = {
settings: { name: value },
init: function(){ 'use strict';
s=this.settings;
this.getApiData(s.name);
},
getApiData: function(attr){
path = '/api/'+attr;
console.log('Get from: ' + path)
var jqxhr = $.ajax({
url: path,
method: "GET",
dataType: "json",
async: false
})
.done(function(responseData){
console.log('Response is: ' + responseData)
// Log: Response is: [object Object],[object Object]..
return responseData
})
}
}; //end
setApiProp.init()
}
unitone.js
Inside a dom content loaded event:
var retrievedData = globalApi("news/")
console.log('Retrieved is: ' + retrievedData)
developersFunction(retrievedData);
The call from unitone.js generates the correct path and gets the correct data in globalApi. However, my log is currently;
Response is: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Retrieved is: undefined
Developer function data is: undefined
My question is; Is there a reliable way to make the developersFunction wait until retrievedData is set, so that it can be used in local functions?
Diagram of requirement: Unit files to call function from central location