Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
Submit Ajax form after Validation

I have a limited understanding of JavaScript, but with some copying and pasting I managed to make a form that gets sent via AJAX.

I'm also running the standard Boostrap 5 input validation. It all worked fine until I found out AJAX fires even without some fields missing.

Then I tried to put the AJAX stuff inside the validation function, but now I need to press "Submit" twice. I understand why, but I don't know how to solve it and would need some help.

This is what I came up with:

(function () {
  'use strict'

  // Fetch all the forms we want to apply validation styles to
  var forms = document.querySelectorAll('.needs-validation')

  // Loop over them and prevent submission
  Array.prototype.slice.call(forms)
    .forEach(function (form) {
      form.addEventListener('submit', function (event) {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
        } 
    
        form.classList.add('was-validated')
        
        var frm = $('#orderform');
        frm.submit(function (e) {
                var formData = {
                firstName_r: jQuery('#firstName_r').val(),
                lastName_r: jQuery('#lastName_r').val(),
                action:'the_ajax_mail'
            };
            $.ajax({
                type        : 'POST', 
                url         : "<?php echo admin_url('admin-ajax.php'); ?>",
                data        : formData,
                encode      : true
            }).done(function(data) {
                console.log(data);        
                form.classList.remove('was-validated');
                document.getElementById('submitForm').disabled = true;
            }).fail(function(data) {
                console.log(data);
            });
            e.preventDefault();     
        });


        
      }, false)
    })
})()

I know the part with var frm = $('#orderform'); and frm.submit(function (e) { needs to go, but I have no idea how...

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Try this

(function() {
  'use strict'

  // Fetch all the forms we want to apply validation styles to
  var forms = document.querySelectorAll('.needs-validation')

  // Loop over them and prevent submission
  Array.prototype.slice.call(forms)
    .forEach(function(form) {
      form.addEventListener('submit', function(event) {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
          return
        }

        form.classList.add('was-validated')

        var formData = {
          firstName_r: jQuery('#firstName_r').val(),
          lastName_r: jQuery('#lastName_r').val(),
          action: 'the_ajax_mail'
        };
        $.ajax({
          type: 'POST',
          url: "<?php echo admin_url('admin-ajax.php'); ?>",
          data: formData,
          encode: true
        }).done(function(data) {
          console.log(data);
          form.classList.remove('was-validated');
          document.getElementById('submitForm').disabled = true;
        }).fail(function(data) {
          console.log(data);
        });
        e.preventDefault();


      }, false)
    })
})()

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda