How to delete data from table using ajax with php and mysql?

Delete Data using Ajax

Table

File name : index.php

CREATE TABLE `posts` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
`content` text NOT NULL,
`link` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

config.php

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}

File name : html page

<div class='container'>
<table border='1' >
<tr style='background: whitesmoke;'>
<th>S.no</th>
<th>Title</th>
<th>Operation</th>
</tr>

<?php
$query = "SELECT * FROM posts";
$result = mysqli_query($con,$query);

$count = 1;
while($row = mysqli_fetch_array($result) ){
$id = $row['id'];
$title = $row['title'];
$link = $row['link'];

?>
<tr>
<td align='center'><?php echo $count; ?></td>
<td><a href='<?php echo $link; ?>'><?php echo $title; ?></a></td>
<td align='center'>
<span class='delete' id='del_<?php echo $id; ?>'>Delete</span>
</td>
</tr>
<?php
$count++;
}
?>
</table>
</div>

File name : remove.php

<?php
include "config.php";

$id = $_POST['id'];

if($id > 0){

// Check record exists
$checkRecord = mysqli_query($con,"SELECT * FROM posts WHERE id=".$id);
$totalrows = mysqli_num_rows($checkRecord);

if($totalrows > 0){
// Delete record
$query = "DELETE FROM posts WHERE id=".$id;
mysqli_query($con,$query);
echo 1;
exit;
}
}

echo 0;
exit;

Ajax function

File name :

$(document).ready(function(){

// Delete
$('.delete').click(function(){
var el = this;
var id = this.id;
var splitid = id.split("_");

// Delete id
var deleteid = splitid[1];

// AJAX Request
$.ajax({
url: 'remove.php',
type: 'POST',
data: { id:deleteid },
success: function(response){

if(response == 1){
// Remove row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(800,function(){
$(this).remove();
});
}else{
alert('Invalid ID.');
}

}
});

});

});





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here