Buttons generated by foreach only execute ajax in the order they are displayed

1

Hello! I am using an ajax on a button so when I click on it it submits a form, the button then changes from VALID to VALIDATED, all without reloading the page.

Here is the code:

$('#validar_form').submit(function(event){
  $.ajax({
    url: 'valida_horaextrarh.php',
    type: 'post',
    dataType:'html',
  data: $('#validar_form').serialize(),
  success: function(response, textStatus, jqXHR){
    $('#principal').html(response);
  },
  error: function(jqXHR, textStatus, errorThrown){
    console.log('error(s):'+textStatus, errorThrown);
  }
 });
});

The problem is that the current code only allows me to click on the buttons in the order they are displayed, image below:

If I try to validate the request of Person 3, I need to validate Person 2 first, otherwise the button does not execute ajax.

How do I resolve this so that I can click the buttons in any order?

    
asked by anonymous 26.04.2018 / 16:24

1 answer

1

This code below is not the best way to do this, I think. But I do not know what would be the most elegant way to do it.

Create forms with foreach :

<?php foreach ($linhas as $linha): ?>
    //Cria o form aqui. Observe o ID.
    <form id="#validar_form<?=$linha['id']?>">
        <button onclick=ajax(<?=$linha['id']?>)>Validar</button>
    </form>
<?php endforeach ?>

Note that I've concatenated a unique key that comes from the bank inside id html. And I added a function called ajax inside the button.

Make the request via ajax :

function ajax(id) {
$.ajax({
        url: 'valida_horaextrarh.php',
        type: 'post',
        dataType:'html',
        data: $('#validar_form'+id).serialize(),
        success: function(response, textStatus, jqXHR){
            $('#principal').html(response);
        },
        error: function(jqXHR, textStatus, errorThrown){
            console.log('error(s):'+textStatus, errorThrown);
        }
    });
}

Note that the information that is serialized by ajax is form with id single now.

    
26.04.2018 / 17:58