let's say I have 5 rows of data, is there a way where I can display the data on its row? how? in my code, when I hit the button on row 5 the result displays in data column.
<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)
}
})
})
In your AJAX success / done handler, traverse up from the current button to a sensible parent (<tr>) then down to the .data element
$('.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 ¯\_(ツ)_/¯
})
})
See .closest()
Did you know, you might not need 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})
}
}
})