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?– Tony
the Alert that displays the result variable Alert(result); is returning the correct code: 46, but when I call the function is always 0
– Luciano
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
– Guilherme Nascimento
I have a notion, but I will give an in depth on the subject. Thank you!
– Luciano
@Guillhermenascimento I was sure it was duplicate, but had not found the previous question.
– Victor Stafusa
@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 :/
– Guilherme Nascimento