digamos que tengo 5 filas de datos, ¿hay alguna forma de mostrar los datos en su fila? ¿cómo? en mi código, cuando presiono el botón en la fila 5, el resultado se muestra en la columna de datos.
<table> <th>action</th><th>data</th> <tr> <td> <button class="getdata" type="button" data-id="1"> </td> <td> <i class="data"></i> </td> </tr> <tr> <td> <button class="getdata" type="button" data-id="2"> </td> <td> <i class="data"></i> </td> </tr> <tr> <td> <button class="getdata" type="button" data-id="3"> </td> <td> <i class="data"></i> </td> </tr>.... </table> $('.getdata').click(function(){ var id = $(this).attr('data-id'); $.ajax({ url: 'log.php', method: 'GET', data:{id:id}, success:function(){ $('.data').html(id) } }) })En su controlador de éxito/hecho de AJAX, recorra hacia arriba desde el botón actual hasta un padre sensato ( <tr> ) y luego hacia abajo hasta el elemento .data
$('.getdata[data-id]').on("click", function() { const btn = $(this) $.get("log.php", { id: btn.data("id") }).done(data => { btn.closest("tr").find(".data").html(id) // or data ¯\_(ツ)_/¯ }) })Ver .más cercano()
¿Sabías que es posible que no necesites jQuery?
// using event delegation at the <table> level document.querySelector("table").addEventListener("click", async e => { const btn = e.target.closest("button.getdata[data-id]") if (btn) { // the click came from a button const id = btn.dataset.id const params = new URLSearchParams({ id }) const res = await fetch(`log.php?${params}`) const data = await res.text() if (res.ok) { btn.closest("tr").querySelector(".data").innerHTML = id // or data } else { console.error(res.status, data}) } } })