Ajax Tutorial
- What is Ajax
- How Ajax Work
- ajax() and load() Function
- AJAX get() and post() Methods
- AJAX Function
- Ajax Success
- Ajax Button Click
- Ajax div load on button click
- Insert Data
- Delete Data
- User Registration
- ContactUs Form
- Check existing Password in Ajax and change the Password
- Ajax Search
- Ajax Serialize Insert
- Ajax without Searialize Insert
- Ajax User Check Availability
- Ajax OptionBox
- Ajax Dropdown Session
- dynamic text box Add/Remove
- Star Rating
- Pin Check Available
- Ajax Programs
- Clear Form Field after submitting form
- Loader load show / hide
- Multiple Functions
Customer Say
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.');
}
}
});
});
});
File name : index.php
File name : index.php