Explanation of the problem.
The A in Ajax means Asynchronous; this means that the request is outside the normal flow of execution. In your code the $.ajax
, when executed, continues the return, return resultado
, and this is executed before the ajax function or request passes the value of the response to the success. Therefore when you use the alert it returns empty or undefined, since the request you made has not returned.
Possible solutions you can give to your problem:
Use callback functions:
A callback is a function that will be invoked later when the Ajax request is finished.
Example:
function hacerPeticionAjax(url, callback) { // callback es solo el nombre de la variable
$.ajax(url, {
// ...
success: callback,
// ...
});
}
function alRecibirAnimales(animales) {
// animales contendrá la respuesta al ajax
}
hacerPeticionAjax('/api/animales', alRecibirAnimales);
This example demonstrates that the success
property must receive a function, which jQuery will invoke upon completion of the request if successful. By the way, there is another callback available to control what to do in case of errors. It is handled using the property error
; receives a callback that will be invoked in case of non-success.
Use the promises:
Promises are containers of future values. When a promise receives the value if it was resolved or canceled, it will notify listeners who want to access that returned value. One of the added values is that it has a higher code reading and in my opinion it is a much better approach. Example:
function delay() {
// 'delay' returns a promise
return new Promise(function(resolve, reject) {
// Only 'delay' is able to resolve or reject the promise
setTimeout(function() {
resolve(42); // After 3 seconds, resolve the promise with value 42
}, 3000);
});
}
delay().then(function(v) { // 'delay' returns a promise
console.log(v); // Log the value once it is resolved
}).catch(function(v) {
// Or do something else if it is rejected
// (it would not happen in this example, since 'reject' is not called).
});
Use Jquery Deferred
This is a customized implementation of the promises implemented by jQuery; the use is very similar to the point explained above:
function ajax() {
return $.ajax(...);
}
ajax().done(function(result) {
// Code depending on result
}).fail(function() {
// An error occurred
});
Source - How do I return the response from an asynchronous call?