There are many ways AJAX can enhance user experience, such as adding, editing, or deleting records without reloading the page. With only PHP, deleting records often involves submitting the page or sending values via URL, resulting in page reloads with each deletion.
However, jQuery AJAX offers a more seamless solution. By passing the record ID via AJAX, you can delete records without reloading the page.
In the example, I’m creating an HTML table displaying a list of records with a delete button. Upon button click, the corresponding record is removed, and the HTML table row fades out as an effect.
Table of Content
- Create a Table
- Create a Database connection file
- Create HTML Layout
- Create AJAX file to Delete record
- jQuery – Send AJAX request to Delete record
- Demo
- Conclusion
1. Create a Table
I am using posts
table in the example.
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 );
2. Create a Database connection file
Create a config.php
file for the database connection.
<?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()); }
3. Create HTML Layout
Display the records from the posts table in a <table>
format. Additionally, I’ve incorporated a <span>
element with the class ‘delete’ to facilitate the deletion of records, storing the delete ID in the data-id variable.
Full Code
<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'><?= $count; ?></td> <td><a href='<?= $link; ?>'><?= $title; ?></a></td> <td align='center'> <span class='delete' data-id='<?= $id; ?>'>Delete</span> </td> </tr> <?php $count++; } ?> </table> </div>
4. Create AJAX file to Delete the record
Create a remove.php
file to manage AJAX requests.
Retrieve the ID from the POST request.
Verify if a record exists in the posts
table. If a record is found, execute the delete query using the provided ID, returning 1. If no record is found, return 0.
Full Code
<?php include "config.php"; $id = 0; if(isset($_POST['id'])){ $id = mysqli_real_escape_string($con,$_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; }else{ echo 0; exit; } } echo 0; exit;
5. jQuery – Send AJAX request to Delete record
- Define a click event on the delete class.
- Retrieve the delete ID from the data-id attribute and assign it to the deleteid variable.
- Initiate an AJAX POST request to the ‘remove.php’ file, passing deleteid as data.
- Upon successful AJAX callback, verify the response.
- If the response equals 1, remove the row using remove() and apply a fadeOut() effect to introduce a delay.
- If the response is not equal to 1, display an alert with the message ‘Invalid ID.’.
Full Code
$(document).ready(function(){ // Delete $('.delete').click(function(){ var el = this; // Delete id var deleteid = $(this).data('id'); var confirmalert = confirm("Are you sure?"); if (confirmalert == true) { // 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.'); } } }); } }); });
6. Demo
7. Conclusion
In this post, I’ve demonstrated how AJAX can streamline the deletion of existing records from a MySQL Table, thereby enhancing user interaction. While I showcased its implementation with an HTML table, it’s worth noting that AJAX can be seamlessly integrated with other elements such as <div> and <ul>.
By leveraging jQuery AJAX, we circumvent the need for page reloads traditionally associated with PHP-based record deletion. This method empowers developers to delete records dynamically, offering a smoother user experience.
If you found this tutorial helpful then don't forget to share.
Thanks for creating this post. And, not making it too long 🙂 I don’t write jquery often enough to not usually need a reference to see how the syntax should go. This is a great solution for exactly what I needed to do. It’s nice to find something relevant outside of Stack Overflow.
Thanks.
I can’t make … Delete clickable. Can you please explain how you make it possible?
Hi Liam,
Here, is the short explain –
On the delete button, I use the posts table “id” value to set id attribute e.g. del_1, del_2,etc.
On the button click split the id by “_” to get to delete record id (deleteid = splitid[1]) and pass in the $.ajax request. In PHP file execute DELETE query on the POST id.
thanks a lot.
Glad it was helpful.
Hey, I can delete the row from html table but not from mysql DB. What do i do ?
Hi Rishikesh,
If you are properly removing a row from HTML table means your AJAX request working fine.
Check your AJAX php file.
I have the same issue. Remove.php is set up properly and I copied your ajax code exactly but i’m not getting the $id variable through post and it isn’t removing the row from my database. Can you help?
Can you mail me your files and the database at makitweb@gmail.com so I can check it and help you to resolve the issue.
hi me iam also facing the same problem
Thanks for this tutorial. If I want to delete from multiple tables, will the other delete queries go to remove.php? And how, please?
Yes, all delete queries will be defined in remove.php file.
Thanks for this amazing tutorial.
I would like to clear one thing though, while deleting works perfectly, I was wondering if we could make the Sl no change as well instantly. It takes a refresh to update Sl no.
To update the numbering of S.no after removing record you can either send AJAX request to fetch all records and update the table or loop on the table row using jQuery to update the S.no column value.
I tried incorporating this code to my project but It is not goin well for me. I am new to Jquery, that’s probably the reason why
Can you share me your code at makitweb@gmail.com so I can check?
i cant click on delete button under operations..
Hi Anjali,
Can you share me your code at makitweb@gmail.com so I can check?
Thank you so much! This is awesome!!! You are so very generous, and I appreciate it.
You’re welcome.
Hello sir plz send me the code of this in my gmail id ‘himanisengar0@gmail.com’
Download link is available in the tutorial from where you can download.
How insert alert before delete?
Hi Suwena,
You can add your confirmation alert before sending AJAX request on Delete click.
Excellent Script . keep it up
Thanks.
I didn’t understand how much files to create, and the codes for which files are.. can you explain it please?
Hi Mariam,
You need to create 2 files – index.php and remove.php. In index.php file write HTML and jQuery code and in remove.php write PHP code.
Hi Yogesh! Great job showing and explaining how to delete a record.
Wondering if you can help? I keep getting an Invalid ID alert.
My code is here https://docs.google.com/document/d/1bDGbeh4o6PQ_cGLLll0BGevjez_-q4KjffiQwiEEanw/edit?usp=sharing
Hi Steve,
Have you checked the SELECT query in deleteRecord.php file? Is it correct?
I have the same issue. I have emailed my code
You can add if(response != null) instead of if(response == 1).
Hope will answer and solve your project
Yogesh Singh : I have renamed “remove.php” and then all failled. ¿Do you explain me please?
Thank!
Hi Luis,
Have you also updated the file name in jQuery AJAX script?
Yes Yogesh, i have renamed the script.js. file in “Ajax request url:’removedp.php’ “.
it was called before ‘removed.php’.
What else to do?
Thank!
Sorry,
it was called before ‘remove.php’.
Now the name is ‘removep’
What else to do?
Thank!
Hi Luis,
If you renamed the ‘remove.php’ then only need to update the $.ajax url: ‘removep.php’ in jQuery script.
Yogesh: Could there be another reference to the remove file?
Yogesh: A line I have added and now it works.
I share it with you.
// AJAX Request
$.ajax({
url: ‘removeproducto.php’,
cache: false, <– This is a line.
type: 'POST',
best regards
what i have to edit in ajax code if i have sno instead of id in my database
Hi Priyanshu,
You need to update the HTML and PHP script –
In HTML –
In PHP –
Working like it should, great post!!
this is what I was looking for last 2 days , Working perfectly like it should. Thanks man , big up for your script.
You’re welcome.
Big Thanks Man.
This has been giving headache for 3 days now.
I’m glad you found it useful.
Not working for me… ajax request fails. and throws the invalid id error. anu suggestions?
Works perfect. Thanks. Exactly what i wanted.