.


Divya

How to Delete Data using PHP Ajax


Here we using 2 file for delete data from MySql database using Ajax.

  1. index.php
  2. delete-ajax.php

Table user_data

CREATE TABLE `user_data` (
`id` int(11) NOT NULL,
`Name` varchar(100) NOT NULL,
`email` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

index.php

<?php
$con=mysqli_connect("localhost","root","","php_ajax");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM user_data");
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
table, td, th {
border: 1px solid #ddd;
text-align: left;
}
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 15px;
}
</style>
</head>
<body>
<table>
<tr>
<th>id</th>
<th>StudentName</th>
<th>Student Email</th>
<th>Action</th>
</tr>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<tr>
<input type="hidden" name="id[]" id=<?php echo "id".$i; ?> value="<?php echo $row["id"]; ?>">
<td ><?php echo $row["id"]; ?></td>
<td><input type="text" id=<?php echo "name".$i; ?> value="<?php echo $row["Name"]; ?>"></td>
<td><input type="text" id=<?php echo "email".$i; ?> value="<?php echo $row["email"]; ?>"></td>
<td style="width:270px">
<button type="button" id="<?php echo $row["id"]; ?>" name="submit" class="delete btn btn-success">Delete</button></td>
</tr>
<?php
$i++;
}
?>
</table>
<script>
$(".delete").click(function() {
window.alert("edit Clicked with: "+this.id);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if ( this.status == 200) {
location.reload();
}
};
xmlhttp.open("GET", "delete-ajax.php?id="+this.id, true);
xmlhttp.send();
});
</script>
</body>
</html>

delete-ajax.php

<?php
$conn=mysqli_connect("localhost","root","","php_ajax");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id=$_REQUEST['id'];
$query = "Delete from `user_data` WHERE id = '".$id."'";
echo("alert('$query');");
$result = mysqli_query($conn,$query) or die(mysqli_error());
echo("alert('$result');");
exit(json_encode($_POST));
?>


.