To return a value from
$.ajax
success function, use a callback parameter.Here's how you do it:
function callAjax(callback) {
$.ajax({
url: 'https://whaa.dev/robots.txt',
success: response => {
callback(response);
}
});
}
callAjax(response => {
// Sitemap: https://whaa.dev/sitemap.xml
console.log(response);
});
Since the success
function is called asynchronously, you cannot return stuff right away:
// WILL NOT WORK!!
function callAjax(callback) {
let value;
$.ajax({
url: 'https://whaa.dev/robots.txt',
success: response => {
value = response;
}
});
return value;
}
const value = callAjax();
You have to use a callback
function (like in the first example), pass the value to the callback
function as a parameter, then perform operations on that value inside the callback
function itself.