Function authorizing or not form Ubmit

Asked

Viewed 47 times

0

I’m trying to run a function in the form Ubmit, it works correctly, but if return true I need the form not sent. It’s being done this way:

    $('#FornecedorNovo').submit(function (e) {
    var url = "/Fornecedor/VerificaInscricao";
    var Insc = $("#InscricaoEstadual").val();
    $.ajax({
        url: url,
        data: { insc: Insc },
        datatype: "json",
        type: "POST",
        success: function (data) {
            if (data.resultado == true) {
                alert('Já existe esta inscrição estadual cadastrada para outro fornecedor.');
                e.preventDefault();
            }
        }
    })

});

But still the form is sent.

  • Puts a return false;

  • 1

    You could make the ajax request synchronous, but ideally let the form be sent and do this validation on the server.

  • 1

    The event is asynchronous, so the function will end before you get the answer via AJAX. Thus, the e.preventDefault() will never run, leaving the form to be submitted normally. But the question is: and if it returns false, what should happen?

  • If it returns false the form must be sent, it is sending anyway. In another function I do in Submit I use the e.preventDefault() and it works.

  • @Pedroaugusto I tried, but still the form is sent.

  • What is the best way to check ?

Show 1 more comment

1 answer

1


The code below can solve your problem.

$('#FornecedorNovo').submit(function (e) {
    e.preventDefault(); // Coloca o preventDefault no início da função

    var url  = "/Fornecedor/VerificaInscricao";
    var Insc = $("#InscricaoEstadual").val();
    var form = this,
       $form = $(form); // Salvamos o formulário atual em uma variável

    $.ajax({
        url: url,
        data: { insc: Insc },
        datatype: "json",
        type: "POST",
        success: function (data) {
            if (data.resultado == true) {
                alert('Já existe esta inscrição estadual cadastrada para outro fornecedor.');
            } else {
                $form.off('submit').submit();
            }
        }
    })
});
  • I need to call another function just below, passing another url and if it is true also cannot send the form, will not give problems?

  • I tried so calling the Function on else and returns me error. Why is it returning ?

  • Mariana tries to debug step by step.

Browser other questions tagged

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