Use the callback of a function

2
$(function () {
$("#formulario").submit(function() {
    var cidade_nome = $('#cidade option:selected');
    var ano1 = $('#ano1').val();
    var ano2 = $('#ano2').val();
    var registro;
    var param_1;
    var resposta;
    $.post('envia.php', {cidade: cidade_nome[0].value}, function(retorno) {
    retorno = JSON.parse(retorno);
    console.log(retorno) //sai certo
    });
    //queria usar aqui
    console.log(retorno) //ele sai como undefined no console

I'm trying to use the callback function, ie the variable 'return' outside of it (function), I searched a lot in the forum and the most talked about reason is because it is asynchronous, however I did not get to a solution.

    
asked by anonymous 12.02.2015 / 22:15

2 answers

4

The AJAX is asynchronous. This means that if you have this code for example:

$.post('envia.php', {cidade: cidade_nome[0].value}, function(retorno) {
    // fazer algo quando o AJAX tiver sucedido
});
alert('SOpt');

alert will be run before from function(retorno) { . This function will only be run when AJAX receives the response from the server, and the retorno variable will only receive its value at that point in that scope.

One option is to use async: false , but in 99.8% of the time it's a bad solution and an escape from understanding how JavaScript works. So what you must do is have a function that runs what you need, in the right scope. That is a solution that makes use of "Control flow".

When you say you want to "use the return variable outside of it (function)" I suggest you invert the problem and think what other variables you need to have in the scope of this function?

One solution is to simply define this function before ajax and pass it as an argument to $.post() :

var el = document.querySelector('xpto');
function fnRetorno(retorno){
    el.innerHTML = retorno;
}
$.post('envia.php', {cidade: cidade_nome[0].value}, fnRetorno);

If you better explain what functionality you're missing, I can help you fine-tune the answer.

    
12.02.2015 / 23:27
1

The $ .post method is asynchronous, so it will run after the form is submitted, so you will have to do a synchronous execution, so you will have to use $ .ajax with async = false.

var onSucess= function(retorno) {
    retorno = JSON.parse(retorno);
    console.log(retorno);
};
$.ajax({
    async: false,
    type: "POST",
    url: 'envia.php',
    data: {cidade: cidade_nome[0].value},
    success: onSucess
});
    
12.02.2015 / 23:08