Failure return on Submit

Asked

Viewed 47 times

0

I have a Ubmit, which before I perform this function:

$('#modelEditar').submit(function (e) {
var cancelada = $("#Cancelada").val();
if (cancelada == "False") {
    e.preventDefault();
    var id = document.getElementById("nfseid").value;
    var valores = [];
    $('.item').each(function () {
        var entidade = {
            NFSeId: id,
            ProdutoId: parseInt($(this).children()[10].innerText),
            Id: parseInt($(this).children()[11].innerText),
            Codigo: ($(this).children()[1].innerText),
            Descricao: ($(this).children()[2].innerText),
            UnMedida: ($(this).children()[3].innerText),
            Qtd: ($(this).children()[4].innerText),
            ValorUnitário: parseFloat($(this).children()[5].innerText),
            Deducao: parseFloat($(this).children()[6].innerText),
            DescontoCondicionado: parseFloat($(this).children()[7].innerText),
            DescontoIncondicionado: parseFloat($(this).children()[8].innerText),
            ValorTotal: parseFloat($(this).children()[9].innerText),
        };
        valores.push(entidade);
    });
    var obj = {};
    obj.valores = valores;
    var form = this,
        $form = $(form);

    $.ajax({
        url: "/NFSe/SalvaNFSItens",
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(obj),
        success: function (data) {
            if (data.sucesso == true) {
                if ($('#modelEditar').valid()) {
                    $form.off('submit').submit();
                    if (data.sucesso == false) {
                        console.log('entrou no falso');
                    }
                }
        }
    })
}
else {
    e.preventDefault();
    $("#mensagemalerta").html("NFSe já cancelada, não sendo possível a substituição/alteração.");
    $("#alerta").show();
    $("#alerta").fadeTo(3000, 500).slideUp(500, function () {
        $("#alerta").slideUp(500);
    });
}
})

If it returns everything ok, it continues the Ubmit, but in the errors I always return:

return Json(new { resultado = ViewData["Mensagem"], sucesso = false });

And when I try Submit it appears to me like this on the form: inserir a descrição da imagem aqui

I wanted to treat this way:

 if (data.sucesso == false)
{
    e.preventDefault();
    $("#mensagemalerta").html(data.resultado);
    $("#alerta").show();
    $("#alerta").fadeTo(3000, 500).slideUp(500, function () {
        $("#alerta").slideUp(500);
    });
}

However I am not sure how to use correctly, to inform the error dynamically to the user.

  • Tried to decode JSON with JSON.parse(data) before accessing the values?

  • No, how can I?

  • Add that code snippet data = JSON.parse(data) before if (data.sucesso == true)

  • I tried to put here if ($('#modelEditar').valid()) {
 data = JSON.parse(data);
 console.log(data);
 //$form.off('submit').submit();

 } However it is returning the error Unexpected token o in JSON at position 1

  • It has to be in Success

  • It’s because I have a comeback, and then I have another ($('#modelEditar').valid()) I have another return, if I put before, it will always be true, because it is catching the first, I need the next return

  • If it doesn’t work, remove this code I told you about and change your dataType: "json" capital letters, like this : dataType: "JSON",

  • I think I got your question wrong. You’re already getting the value correctly with parsed JSON... What’s the problem actually?

Show 3 more comments

1 answer

1

If I understand what is happening, the server response is a JSON containing the key

{
  resultado: "Cógido: 0000 ... tente novamente", 
  sucesso: false
}

In your code snippet there is a logical error inside the key 'Success' in the AJAX request, because even if the API returns 'success = false', to request did not fail, then I suggest you do it this way:

$.ajax({
    url: "/NFSe/SalvaNFSItens",
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify(obj),
    success: function (data) {
        if (data.sucesso == true) {
            if ($('#modelEditar').valid()) {
                $form.off('submit').submit();
                if (data.sucesso == false) {
                    console.log('entrou no falso');
                }
            }
        } else {
            $("#mensagemalerta").html(data.resultado);
            $("#alerta").show();
            $("#alerta").fadeTo(3000, 500).slideUp(500, function () {
                $("#alerta").slideUp(500);
            });
        }
})

Browser other questions tagged

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