AJAX Multiples submit in a form

1

I need to have 2 or more buttons in a FORM and each with a different action, I know that I can do this directly with HTML by adding a formaction but I need to do this from AJAX , I am also aware that I can use a onclick on each button, but I need it to be submit so that html is in charge of doing all the validations of the form, since there are fields with the required attributes, maxlength, email, number, etc.

It would be something like this that I need:

$(function(){
  $('form').submit(function(event){
   event.preventDefault();
   /*Codigo Ajax*/
  });
});

<form>
 <input type="text" name="usuario" required/>
 <input type="password" name="password" required/>
 <button formaction="login.php"></button>
 <button formaction="registro.php"></button>
</form>
    
asked by StevePHP 04.05.2018 в 15:36
source

2 answers

0

You can use document.activeElement to get the button that was used and then get formaction with the .attr() method of jQuery.

$(function(){
  $('form').submit(function(event){
   event.preventDefault();
   var action = $(document.activeElement).attr('formaction');
   
   // imprime "login.php" o "registro.php"
   console.log(action);
   
   /*Codigo Ajax*/
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
 <input type="text" name="usuario" required/>
 <input type="password" name="password" required/>
 <button formaction="login.php">login</button>
 <button formaction="registro.php">registro</button>
</form>
    
answered by 04.05.2018 в 16:40
0

I was able to resolve this issue thanks to the jquery plugin jqueryvalidation It's incredibly easy to use.

The code was as follows:

<script>
  $(function(){
    $('form').submit(function(event){
      event.preventDefault();
    });
  });

  function Registro(){
    /*
       EL PLUGIN HACE LAS VALIDACIONES DEL 
       FORMULARIO Y RETORNA TRUE O FALSE
    */ 

    if( $("form").valid() ){
      /* CODIGO AJAX PARA REGISTRAR USUARIO */
    }
  }

  function Login(){
    /*
       EL PLUGIN HACE LAS VALIDACIONES DEL 
       FORMULARIO Y RETORNA TRUE O FALSE
    */ 

    if( $("form").valid() ){
      /* CODIGO AJAX PARA INICIAR SESION */
    }
  }
</script>

 <form>
   <input type="text" name="usuario" required/>
   <input type="password" name="password" required/>
   <button type="button" onclick="Login()">Iniciar Sesion</button>
   <button type="button" onclick="Registro()">Registro</button>
 </form>
    
answered by 04.05.2018 в 16:45