preventDefault () - Before sending by PHP A BBDD (jQuery)

1

I try to send the information of a form, to a database, so before sending it, I want to check that all the fields that I have marked with "required" are filled in.

For this I am trying the following:

$("#comprobarDatos").on("click", function(e){     
if(!valid) {
        e.preventDefault();
      } else {
        $.ajax({
          type: 'POST',
          url: 'php/enviar_pedido.php',
          data: {'referencia': referencia, 
                 'detalles': detallesCi,
                 'tipo': tipoCi,
                  ...etc
                  }
        })
        .done(function(){
          alert('Pedido enviado con éxito');
        })
        .fail(function(){
          alert("Error 01");
        })
})

This is the INPUT:

<input type="submit" id="comprobarDatos" value="Comprobar Pedido">

If it validates that the fields are in required. However, it does not execute anything from the AJAX.

Thank you.

    
asked by Javier Avila Fernandez 27.08.2018 в 16:58
source

2 answers

2

You could do it like this:

$("#tuformulario").on("submit", function(e){
  e.preventDefault(); // Para no realizar el action del form
  $.ajax({
    type: 'POST',
    url: 'php/enviar_pedido.php',
    data: {'referencia': "test", 
           'detalles': "test2"}
  })
  .done(function(){
    alert('Pedido enviado con éxito');
  })
  .fail(function(){
    alert("Error 01");
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="tuformulario">
  <input name="referencia" id="referencia" required />
  <input name="detalles" id="detallesCi" required />
  <input type="submit" id="comprobarDatos" value="Comprobar" />
</form>

When doing so with onsubmit you will see that the browser itself slows you down if the required fields are not filled correctly, so you would not need to use checkValidity .

I also leave you link to checkValidity documentation.

    
answered by 27.08.2018 / 17:29
source
0

use the submit method in the form and as you send the data by ajax place a return false

$("#form").submit(function(){
  $.ajax({
    type: 'POST',
    url: 'php/enviar_pedido.php',
    data: {'referencia': "test", 
           'detalles': "test2"}
  })
  .done(function(){
    alert('Pedido enviado con éxito');
  })
  .fail(function(){
    alert("Error 01");
  });
  return false;
})

the validation leave it to the requied

    
answered by 27.08.2018 в 17:34