I am calling a function that returns the result of an ajax GET request using jQuery.
How do you return its result through the function to the callee?
function makePrPoContent(s_firstName, s_lastName, s_email){
$.get('/includes/snippets/privacy_policy.jsp', {
firstName: s_firstName,
lastName: s_lastName,
email: s_email
}, function(data){
return data;
});
}
var mainContent = makePrPoContent('Stack', 'Overflow', 'email@fake.com');
console.log(mainContent);
The above doesn’t return anything, probably since the return is within the ajax callback, so therefore the return doesn’t return to makePrPoContent.
Also tried this:
function makePrPoContent(s_firstName, s_lastName, s_email){
var returnData = false;
$.get('/includes/snippets/privacy_policy.jsp', {
firstName: s_firstName,
lastName: s_lastName,
email: s_email
}, function(data){
returnData = data;
});
return returnData;
}
That doesn’t work because it returns before the ajax call is finished, therefore returnData is still false.
I can verify that there is indeed data returned through the ajax callback. When I log the data in the callback it has what I need.
How would I get this to return to my function?
Thanks for the help in advance!
AJAX is asynchronous, so you can best approach it that way, you can change the function like this:
Then when you call it, you pass in the function that takes the result, like this: