So I'm trying to setup a website that uses PHP but has no PHP on it, so all of the PHP is bridged with AJAX and jQuery. So I'm trying to setup the user system to work on the same bases and to make things easier I want to have some jquery functions that get information from the database. Let's say a jQuery function that gets the first name of the logged in user:
function postData(dataString, url, type, callback){
var request = $.ajax({
url: url,
method: "POST",
data: dataString,
dataType: "JSONP",
async: true,
success: function(data){
console.log("Server Responce: " + data.value);
if(callback != null){
return callback(data);
}
},
error: function(jqHXR, textStatus){
console.log("Server Error: " + textStatus);
}
});
return request;
}
So for example sakes this is the function that runs the AJAX call. It is called as a variable which is request which returns nothing. I also have a call back however I don't want to use this all the time if it's avoidable. Below you can see what I want to be able to do.
function getFirstName(userId){
return postData("userId=" + userId, "getFirstName.php", "GET", null);
}
function useFirstName1(userId){
rndElement.innerHTML = getFirstName(userId);
}
function useFirstName2(userId){
rndElement2.innerHTML = getFirstName(userId);
}
So as you can see I have one function which works with the AJAX function which is getFirstName and then I have two which depend on this function to retrieve the first name of the user useFirstName1 and userFirstName2. What I'm trying to achieve is away that when AJAX has got the JSON from the php file it sends it to the getFirstName function which would of called it and then that function returns it to it's own calling function.
Now I've read around and I'm sceptical that there is a solution to this problem and I'm going to need to rely on callback and make the same AJAX request multiple times in different scenarios. I'm not going to put async to false as this defeats the purpose of using AJAX in my opinion and we are all working to a faster more dynamic web and this doesn't help.
All I'm looking for is a simple yes (with guidance) or no whether I can do this or not. Thanks for taking the time to read.