Submit confirm() the Cancel button does not work

Asked

Viewed 127 times

1

I am having a problem where by clicking the Cancel button is not canceling the operation and this continuing and sending the form

<form action="insere_forn.php" class="control-form" method="post" id="forn_cad" name="forn_cad" enctype="multipart/form-data">
    <div class="row">
    <div class="col-6">
      <div class="form-group ">
        <input type="text" name="nome_forn" placeholder="Digite o nome do fornecedor" class="form-control " id="nome_forn" required/>
      </div>
    </div>
    </div>
       <div class="row">
    <div class="col-6">
      <div class="form-group ">
        <input type="text" name="end_forn" placeholder="Endereço" class="form-control " id="end_forn" />
      </div>
    </div>
    </div>
       <div class="row">
    <div class="col-6">
      <div class="form-group ">
        <input type="text" name="telefone_forn" placeholder="telefone" class="form-control " id="telefone_forn" />
      </div>
    </div>
    </div>
       <div class="row">
    <div class="col-6">
      <div class="form-group ">
        <input type="text" name="email_forn" placeholder="email" class="form-control " id="email_forn" />
      </div>
    </div>
    </div>
       <div class="row">
    <div class="col-6">
      <div class="form-group ">
        <input type="text" name="cnpj" placeholder="CNPJ" class="form-control " id="cnpj" />
      </div>
    </div>
    </div>
    <div class="row">
     <div class="col-6">
      <div class="input-group-prepend">
       <div class="custom-file">

     Arquivo: <input type="file" name="arquivo"  class="custom-file-input" id="customFileLang" required  accept=".jpg">
           <label class="custom-file-label" for="customFileLang">Selecione uma foto</label>
      </div>

  </div>
    </div>
    </div>
    <div class="form-group">

    <input type="hidden" name="id_fornc" value="">
    <input type="hidden" name="data_cad_forn" value="">
    </div>
   <div class="form-group">
        <div class="col-6">
            <button type="submit" id="butao"class="btn btn-primary">Cadastrar</button>
        </div>
    </div>

</form> 

i am sending the form via ajax

 $("#forn_cad").submit(function(e) {
    var url2 = "mostra_forn.php";
    var url = "insere_forn.php"; 
     if (confirm('Tem certeza que quer cadastrar o Tipo de forncedor?')){ 

    $.ajax({
           type: "POST",
           url: url,
           data: $("#forn_cad").serialize(),
           success: function(data)
    {
                $("#mostra_forn").fadeOut(800, function(){
                $("#mostra_forn").load(url2).fadeIn().delay(2000);
               });
           }

         });
     }else{ 
           return false 
   }

    e.preventDefault();
});

only that even if I click cancel send the form

upload bar

$(document).ready(function() {
    //elements
    var progressbox     = $('#progressbox');
    var progressbar     = $('#progressbar');
    var statustxt       = $('#statustxt');
    var submitbutton    = $("#butao");
    var myform          = $("#forn_cad");
    var output          = $("#output");
    var completed       = '0%';

    $(myform).ajaxForm({
        beforeSend: function() { 
            submitbutton.attr('disabled', '');
            statustxt.empty();
            progressbox.slideDown(); //exibe a barra de progresso
            progressbar.width(completed); //inicia em 0%
            statustxt.html(completed); //exibe o texto
            statustxt.css('color','#5e72e4'); //define a cor
        },
        uploadProgress: function(event, position, total, percentComplete) { 
            progressbar.width(percentComplete + '%') //atualiza o tamanho da barra
            statustxt.html(percentComplete + '%'); //atualiza o texto
            if(percentComplete>50)
                {
                    statustxt.css('color','#825ee4'); //troca a cor acima dos 50%
                }
            },
        complete: function(response) { // quando completar
            output.html(response.responseText); //exibe a resposta do seu arquivo php... podendo ser a imagem carregada
            myform.resetForm();  // reseta o form
            submitbutton.removeAttr('disabled'); //habilita o botão novamente
            progressbox.fadeOut(1000); // esconde a barra
            }
    });
});
  • Who it should be e on the line e.preventDefault()? Probably in his console appeared the variable indefinite error.

  • Which cancel button?

  • $("#forn_cad"). Ubmit(Function(and) {

  • Friend tries to give e.preventDefault before Return false: e.preventDefault(); Return false;

  • continues sending

  • Dear Daniel, there’s probably something else interfering with the form submission, because in normal cases it’s supposed to work. Just you create a test page and put only this question code and you will see that it will work normally.

  • Another nonsense is to use the action and method attributes in the form if it is sent via Ajax.

Show 2 more comments

1 answer

1

$("form").submit(function(e) {
  e.preventDefault(); // Precisa prevenir o comportamento padrão antes de qualquer coisa
  
  const isConfirmed = confirm('Tem certeza que quer cadastrar o Tipo de forncedor?');
  
  if (isConfirmed) {
    console.log('Ajax request...');
  } else {
    console.log('User did not confirm');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <input type="text" name="" required>
  <button>Cadastrar</button>
</form>

EDIT

I was doing some research on ajaxForm and I think I’ve been able to identify your problem.

The ideal is to always understand the plugins, libraries and frameworks you use in your project.

The ajaxForm is a Jquery plugin created to make requests even easier ajax, preventing the developer from doing the job of identifying the inputs to send the request. See below for a simple request on ajax:

$('#formulario').on('submit', function () {
 
    // Armazenando informações do formulário em variáveis
    var nome = $("input[name=nome]").val();
    var email = $("input[name=email]").val();
    var mensagem = $("textarea[name=mensagem]").val();
 
    // Fazendo requisição AJAX
    $.post(this.action, {nome: nome, email: email, mensagem: mensagem}, function (resposta) {
        console.log(resposta);
    });
 
    // Retorna FALSE para que o formulário não seja enviado de forma convencional
    return false;     
});

Now see that using ajaxForm the code gets much cleaner:

$('#formulario').ajaxForm(function (resposta) {
    console.log(resposta);
});

Then ajaxForm makes the "mapping" of your form, inputs and attributes to create the request, ie as your element form in the HTML file already has the attribute action defined, this will be the value default URL during ajaxForm request.


What I suggest to you is to eliminate this general call to ajaxForm in your code and assign the options in a variable as follows:

var output = $("#output");
var completed = '0%';
var options = {
    beforeSend: function() {
        submitbutton.attr('disabled', '');
        // Restante do código...
};

// $(myform).ajaxForm(); Remova esta instrução

And in your ajax request you make the necessary changes:

$("#forn_cad").submit(function(e) {
    var url2 = "mostra_forn.php";
    var url = "insere_forn.php";
    
    if (confirm('Tem certeza que quer cadastrar o Tipo de fornecedor?')) {

        //Adicionar os valores a variável options
        options.type = 'POST';
        options.url = url;
        options.data = $("#forn_cad").serialize();
        options.success = function(data) {
            $("#mostra_forn").fadeOut(800, function() {
                $("#mostra_forn").load(url2).fadeIn().delay(2000);
            });

        $.ajax(options);
     } else {
         return false;
     }
});

Completion I believe this is a valid option for your project scenario but remember that with each ajax request, some properties of the object should be changed, for example: type, url, data and success.

  • Why you need to "prevent behavior before anything"?

  • he’s still sending even if I cancel

  • @Danielricardo, can you tell if there is any other event "tied" to the element?

  • No need for preventDefault(). Only Return false already cancels Submit. And even if you use preventDefault(), it doesn’t need to come first because the function block runs to the end if it doesn’t enter the Else that has the Return false.

  • the upload bar, she’s tied, she’s the one giving conflto, how do I make this conflict not happen

  • Got it @Sam! Thanks for explaining! @Danielricardo, how’s the upload bar function?

  • @Victorcarnaval I edited and put the upload bar Function

  • @Danielricardo, change your form id. id is set forn_cad, change to any other name that the problem will be solved.

  • @Victorcarnaval tried but if I take out nothing works more

  • @Danielricardo, I updated the answer! Read everything and see if it solves the problem

Show 5 more comments

Browser other questions tagged

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