C
C
Calabozo2020-06-02 02:42:51
AJAX
Calabozo, 2020-06-02 02:42:51

Why does ajax only work on the first row of a table?

Good afternoon.
I ask for help in my suffering. In development, I'm not ale.
Straight to the point...
There is a table with data against each row, the "delete" button (delete the row completely).
In each row of the table, the buttons work, but Ajax still accepts the data of the first object/row of the table.
How to make a button match its line?
HTML source code

table>
    <thead>
        <tr>
            <td>Id</td>
            <td>name</td>
            <td>Удалить</td>
        </tr>
    </thead>
    <tbody>
        <?php foreach($data[0] as $row => $value): ?>
        <tr>
            <td> <?=$value[0]?></td>
            <td> <?=$value[1]?></td>

            <td>
                <form method="POST"  id="form2" action="" >
                    <input  type="hidden" name="del" class="del" value="<?=$value[0]?>"  /><br>
                    <input  value="del"  id="btn2"  type="button" > </form>
            </td>
        </tr>
        <?php endforeach?>
    </tbody>
</table>
<div  id='result_form3'> </div>


Ajax Code
$( document ).ready(function() {
  var elements = document.querySelectorAll('#btn2');
  for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', function(){
      sendAjaxForm1('result_form3', 'form2', 'application/models/forms/del_form.php');
      return false; });
  }

});
 
function sendAjaxForm1(result_form3, form2, url) {
    $.ajax({
        url:     url, 
        type:     "POST", 
        dataType: "html", 
        data: $("#"+form2).serialize(),  
    success: function(response) { 
          	$('#result_form3').html(response);
    },
    	error: function(data) { 
            $('#result_form3').html('Ошибка. Данные не отправлены.');
    	}
 	});
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AUser0, 2020-06-02
@Calabozo

All forms have the same id=form2. Accordingly, JS finds the very first form with this id, and works with it. Change for example to id=form<?=$value[0]?> and it will work.
Of course, after you change 'form2' in sendAjaxForm1() to use the correct id of the corresponding form. Or you can just rewrite the code to use value=<?$value[0]?> from the pressed button.
PS And in general, the forms themselves are not needed if AJAX is used. They should be used for browsers that don't support AJAX. And here they are - completely redundant ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question