Ajax works asynchronously, that is, the request is sent and the rest of the code continues to be executed.
To capture and display the return value of the request, you need to add these functions within the callback
successful.
function getCategoria(id){
$.ajax({
url: "../control/anuncio/index.php",
data:{
method: 'get_categoria',
id_categoria: id
},
method: "post",
dataType: "json",
success: function(retorno){
exibeMensagem(retorno.categoria);
}
});
}
function exibeMensagem(msg) {
alert(msg);
}
Another way is to add the option async:false,
. Ex:
$.ajax({
url: "../control/anuncio/index.php",
async: false,
data:{
method: 'get_categoria',
id_categoria: id
},
But there is a problem. Current browsers display the alert:
Synchronous Xmlhttprequest on the main thread is deprecated because of its detrimental effects to the end user’s Experience. For more help, check https://xhr.spec.whatwg.org/.
The reason? Soon it will be removed and you will not be able to use it. According to the API’s own specification...
Synchronous requests are in the process of removing the web platform as it has detrimental effects to the end user experience.
The developers nay should pass false to the asynchronous argument when the current global object is a Window
. Users are strongly encouraged to warn about such use in development tools and may generate the exception InvalidAccessError
Of course they will not remove one from another, but the ideal is to adapt as soon as possible. So the recommended is you create another function to handle the return of the request (as shown in the first example).
from a console.log(return), and will show us the result.
– RickPariz