Javascript: Function is not returning the correct value [duplicate]

1

What could be wrong with this function? Where alert is, the correct result is coming, but it 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} .

    
asked by anonymous 22.06.2018 / 03:06

1 answer

0

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

    
22.06.2018 / 03:13