We do use 4 file to delete data from MySql database using Ajax.
- database.php
- index.php
- ajax_data.php
- delete_ajax.php
Before to create files you need to create database and then create table following code will help to your database table
CREATE TABLE `user_data` (
`id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`phone` varchar(100) NOT NULL,
`city` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
#database.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "tutorial";
// Create connection to db
$conn = mysqli_connect($servername, $username, $password, $db);
?>
#index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>View Ajax</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h4>View data</h4>
<table class="table table-bordered table-sm" >
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>City</th>
<th>Action</th>
</tr>
</thead>
<tbody id="table">
</tbody>
</table>
</div>
<script>
$(document).ready(function() {
$.ajax({
url: "ajax_data.php",
type: "POST",
cache: false,
success: function(dataResult) {
$('#table').html(dataResult);
}
});
$(document).on("click", ".delete", function() {
var $ele = $(this).parent().parent();
$.ajax({
url: "delete_ajax.php",
type: "POST",
cache: false,
data: {
id: $(this).attr("data-id")
},
success: function(dataResult) {
var dataResult = JSON.parse(dataResult);
if (dataResult.statusCode == 200) {
$ele.fadeOut().remove();
}
}
});
});
});
</script>
</body>
</html>
#ajax_data.php
<?php
include 'database.php';
$sql = "SELECT * FROM user_data";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['phone']; ?></td>
<td><?php echo $row['city']; ?></td>
<td>
<a href="" class="delete" data-id=" <?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php
}
} else {
echo "<tr >
<td colspan='5'>No Result found !</td>
</tr>";
}
mysqli_close($conn);
?>
#delete_ajax.php
<?php
include 'database.php';
$id = $_POST['id'];
$sql = "DELETE FROM `user_data` WHERE id=$id";
if (mysqli_query($conn, $sql)) {
echo json_encode(array("statusCode" => 200));
} else {
echo json_encode(array("statusCode" => 201));
}
mysqli_close($conn);
?>
#output: