Javascript: Function is not returning the correct value

Asked

Viewed 46 times

1

What could be wrong with this function? Where is the alert, is coming the correct result but is returning 0.

function AprovaCotacao(numForn) {
    var forn_aprovado = $("#cot_fornecedor" + numForn).val();
    var id = $("#cot_id").val();
    var url = host + "/cotacoes/Aprovar";
    var result = 0;

    $.ajax({
        url: url
        , data: { id: id, idFornecedor: forn_aprovado, numAprovado: numForn }
        , type: "GET"
        , dataType: "json"
        , contentType: "application/json; charset=utf-8"
        , success: function (data) {
            if (data.mensagem == '') {
                result = data.pedido;
                alert(result);
            }
            else {
                result = -1;
                alert(data.mensagem);
            }
        }
    });
    return result;
}

Result of json: {"mensagem":"","pedido":46}.

  • Has two alert then you can explain further?

  • the Alert that displays the result variable Alert(result); is returning the correct code: 46, but when I call the function is always 0

  • 1

    Luciano the best way to solve this is to understand what is and how it works asynchronously and that wanting to force synchronous in Javascript is unnecessary and probably is because you still do not understand very well the behavior of callback and asynchronous in JS, recommend the links: 1. https://answall.com/q/45706/3635 / 2. https://answall.com/q/16950/3635 3. https://answall.com/q/51268/3635

  • I have a notion, but I will give an in depth on the subject. Thank you!

  • @Guillhermenascimento I was sure it was duplicate, but had not found the previous question.

  • 1

    @Victorstafusa has another 3 like this, even with better answers, but this very complicated to find, even more because if I remember the titles are things like: "problem with ajax", "error in ajax" and "ajax does not work", there is impossible to find :/

Show 1 more comment

1 answer

0

The call $.ajax(...) is asynchronous. That is, she will not make the call immediately, but will post a request for it to be made. Javascript execution will then find the return result; and return zero. Only after that will the AJAX call happen, but then when setting the value of the variable result, it will be too late.

  • I understood, but I read that it is opportune to leave the so-called synchronous, in this way, what would be the best way to solve this problem?

  • @Luciano It depends on which function is calling your AprovaCotacao and what she’s doing with the result. I suggest editing the question to include this.

Browser other questions tagged

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