Submit multiple forms with AJAX, one at a time

2

I have a code that I get with PHP registered students in my bank, and I make a for it to have 1 form for each student. Each form has its button submit, which takes you to the AJAX function to serialize form.

This is my form's tag (which is within PHP's for f)

<form method="post" enctype="multipart/form-data" action="#" id="form1" class="form">

Submit it

<button onclick="saveAluno(); return false" class="btn btn-block btn-primary">

and this is my AJAX to serialize

function saveAluno(){
var data1 = $('.form').serialize();
console.log(data1);
$.post("controller/setters/addAlunoRotina.php", $('#form1').serialize(), function (response) {
    alert("Salvo com sucesso!");
}); }

This way it is serializing all the forms together, all at once. Is there any way I can serialize one by one of these forms?

This is an image of my system forms, so maybe it is easier to understand the problem;

    
asked by anonymous 08.01.2016 / 17:28

2 answers

6

The button will no longer send the form, instead jQuery will capture every time it is clicked. To do this, add in the buttons class the value bt_form

<button class="btn btn-block btn-primary bt_form">

And now add the jQuery code below in place of saveAluno

// Toda vez que algum button for clicado
$('button.bt_form').on('click', function(event){
    event.preventDefault(); // Cancela submit padrão do button

    // Faz a mesma coisa que saveAluno mas usa .closest para pegar o form do button
    var data1 = $(this).closest('form');
    console.log(data1);
    $.post("controller/setters/addAlunoRotina.php", data1.serialize(), function (response) {
        alert("Salvo com sucesso!");
    }); 
});
    
08.01.2016 / 18:32
2

If there are multiple forms, with the same id: Form + Button

Change this:

<form method="post" enctype="multipart/form-data" action="#" id="form1" class="form">

For this (starting from the principle that should be in a loop).

<?
 $i = 0; //EXEMPLO

while($mysql = $mysql->fetch_array()){ // EXEMPLO
?>

<form method="post" enctype="multipart/form-data" action="#" id="form<? echo $i ?>" class="form">

<button onclick="saveAluno(<? echo $i ?>); return false" class="btn btn-block btn-primary">

<?
$i++; //EXEMPLO
} // EXEMPLO
?>
  • Changes: now each form has a unique id.

Javascript

    function saveAluno(id){
var data1 = $('.form').serialize();
console.log(data1);
$.post("controller/setters/addAlunoRotina.php", $('#form'+id).serialize(), function (response) {
    alert("Salvo com sucesso!");
}); }
  • Changes: The button id is the same as form, which has its unique name.
08.01.2016 / 18:30