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

Asked

Viewed 117 times

1

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

Here’s 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 the buttons in the order they are displayed, image below: inserir a descrição da imagem aqui

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

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

  • Each line of this is inside a form ?

  • There is a select collecting the rows in the database, a foreach that tables them for me while there is data, each row generates this button that submits a form to update the line saying that it was checked, the submit of this form uses ajax not to update the page and process the data.

  • I ask the same as @Leandrolima... each line has its own form or the whole block is inside a form? Put the code that is possible to run/test otherwise it will be difficult to help.

  • Each line has a form, I even understood why the question, how it looks for the form ID the problem should be this, ajax stops at the first ID it finds, but how to solve I do not know.

1 answer

1


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

Creates the forms with the 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 ?>

Notice that I concatenei a unique key that is coming from the bank inside the id html. And 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 a form with id only now.

  • 1

    Whether or not it’s the most elegant way I don’t know, BUT IT WORKS! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.