Using the callback of a function

Asked

Viewed 643 times

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 of the function, 'return' out of it(function),searched a lot in the forum and the most talked reason is for being asynchronous, however I could not reach a solution.

  • This http://answall.com/a/45544/3635 and this http://answall.com/a/45721/3635 should also help you

2 answers

4


AJAX is asynchronous. That means if you have for example this code:

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

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

One option is to use async: false, but at 99.8% of the time it is a bad solution and an escape to understand how Javascript works. So what you should 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 variable return out of it (function)" I suggest you reverse the problem and think what other variables you need to have in the scope of this function?

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

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

If you explain better what functionality you lack I can help you adjust the answer.

1

The $.post method is asynchronous, so it will run after sending the form, so you will have to do a synchronous execution, so you will need 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
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.