I have searched all over for this and cannot find a solution. I am still a beginner in both PHP and AJAX, so please bear with me.
I have a file fetch.php which generates content for my page index.html. Fetch.php gets data from a MySQL database and adds it to my index page like this:
while ($res = mysqli_fetch_array($rs)) {
$str .= '<div class="task" id='.$res['tid'].'>
<table>
<tr>
<td>
<button class="btnDelete" data-id="'.$res['tid'].'">x</button>
</td>
<td>'.$res["name"].'</td>
</tr>
<tr>
<td>'. $res["task"].'</td></tr></table></div>';
}
echo $str;
The "tid" being my table index. Now, when I click the button with the data-id of 1, I want to delete the row with the tid of 1.
<script type="text/javascript">
$('.btnDelete').click(function() {
var recordid = $('.btnDelete').data('id');
$.ajax({
type: 'POST',
url: 'remove.php',
data: { 'id': recordid},
});
});
</script>
This sends the (supposed to) data-id to the following PHP.
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
if (!$con) {
die("Can not connect: " .mysql_error());
}
$id = $_POST['recordid'];
$sql = "UPDATE tasks SET visible = 'hide' WHERE tid = $id ";
$query = mysqli_query($con, $sql);
if(mysqli_affected_rows($con)) {
echo "Record deleted successfully";
}
mysqli_close($con);
My PHP files work, but nothing happens when I click the button? Below is my complete HTML:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type="text/javascript">
$(function() {
getStatus();
});
function getStatus() {
$('div#data').load('fetch.php');
setTimeout("getStatus()",300000);
}
</script>
</head>
<body>
<div id="data">
</div>
<script type="text/javascript">
$('.btnDelete').click(function() {
var recordid = $('.btnDelete').data('id');
$.ajax({
type: 'POST',
url: 'remove.php',
data: { 'id': recordid},
});
});
</script>
</body>
</html>
How can I get the AJAX to trigger on the buttonclick and send the data-id to remove.php?
This is not a duplicate, it is an AJAX question and not a MySQL question