jQuery AJAX Delete Data from Database Without Page Reload

In this lesson, you’ll learn how to delete records from a MySQL database using jQuery AJAX and PHP — without refreshing the page.

This technique is widely used in:

  • Admin dashboards
  • Blog management systems
  • User management panels

What You’ll Learn

  • Create a delete button
  • Send record ID via AJAX
  • Delete data using PHP
  • Remove row dynamically
  • Show confirmation before delete

What is AJAX Delete?

AJAX delete means removing data from the database without reloading the page.

👉 In simple terms:
You click delete → data is removed instantly → UI updates dynamically.

This is widely used in:

  • Admin dashboards
  • User management systems
  • Content management systems

👉 It improves speed and user experience.

How AJAX Delete Works

Here’s how the delete process works:

  1. User clicks the delete button
  2. jQuery captures the record ID
  3. Confirmation popup appears
  4. AJAX sends the ID to PHP
  5. PHP deletes the record from database
  6. jQuery removes the row from UI

👉 This allows instant deletion without refreshing the page.

Why Use AJAX for Delete?

Using AJAX for delete operations:

  • Improves user experience
  • Avoids full page reload
  • Makes UI faster and smoother
  • Allows dynamic updates

👉 This is commonly used in admin panels and dashboards.

Step 1: Database Table

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100)
);

Step 2: Display Data with Delete Button

fetch.php

<?php
$conn = new mysqli("localhost", "root", "", "ajax_demo");

$result = $conn->query("SELECT * FROM users");

while ($row = $result->fetch_assoc()) {
    echo "<tr id='row-{$row['id']}'>
            <td>{$row['id']}</td>
            <td>{$row['name']}</td>
            <td>{$row['email']}</td>
            <td>
                <button class='deleteBtn' data-id='{$row['id']}'>Delete</button>
            </td>
          </tr>";
}
?>

Step 3: HTML Table

<table border="1" width="100%">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody id="userData"></tbody>
</table>

Step 4: jQuery AJAX Delete Code

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).on('click', '.deleteBtn', function() {
    let userId = $(this).data('id');

    if (confirm('Are you sure you want to delete this record?')) {
        $.ajax({
            url: 'delete.php',
            type: 'POST',
            data: { id: userId },
            success: function(response) {
                if (response === 'success') {
                    $('#row-' + userId).fadeOut();
                }
            }
        });
    }
});
</script>

Step 5: PHP – Delete Record

delete.php

<?php
$conn = new mysqli("localhost", "root", "", "ajax_demo");

$id = $_POST['id'];

$stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
$stmt->bind_param("i", $id);

if ($stmt->execute()) {
    echo "success";
} else {
    echo "error";
}
?>

Step 6: Auto Reload Table (Optional)

Instead of fading out, you can reload data:

loadUsers();

This keeps UI consistent.

Handling Errors in AJAX Delete

You should always handle errors properly.

$.ajax({
    url: 'delete.php',
    type: 'POST',
    data: { id: userId },
    success: function(response) {
        if (response === 'success') {
            $('#row-' + userId).fadeOut();
        } else {
            alert('Delete failed!');
        }
    },
    error: function() {
        alert('Server error occurred');
    }
});

👉 This ensures better reliability and debugging.

Real Example: Admin Panel

This technique is commonly used in:

  • User management systems
  • Blog post deletion
  • Product management dashboards
  • Admin control panels

👉 Almost every CRUD-based application uses this method.

Improving User Feedback

Instead of just fading out the row, you can:

  • Show success message
  • Display error if deletion fails
  • Add loading indicator

Example:

alert(“Record deleted successfully!”);

When to Use AJAX Delete

Use this method when:

  • You are building dashboards
  • You need quick record management
  • You want smooth UI interactions

Avoid when:

  • Security is critical without authentication
  • You need confirmation logging

FAQs

What is AJAX delete in jQuery?

It allows deleting data from the server without refreshing the page.

Why use POST instead of GET for delete?

POST is more secure and prevents accidental deletions.

How do I confirm delete action?

Use confirm() or libraries like SweetAlert.

Why is my row not deleting?

Check AJAX response and row selector.

Is AJAX delete safe?

Yes, if you use validation, authentication, and prepared statements.

Security Tips

  • Always use prepared statements
  • Validate and sanitize input ID
  • Restrict delete access using authentication
  • Avoid exposing raw database queries
  • Use CSRF protection in real applications

👉 Security is critical when performing delete operations.

Common Mistakes

  • Missing data-id
  • Using GET for delete
  • Not checking response
  • Deleting wrong row selector

Mini Task for Students

  1. Add SweetAlert confirmation popup
  2. Show success/error message after delete
  3. Add undo delete feature
  4. Restrict delete access for admin users only
  5. Reload table after deletion

👉 These tasks will help you build real-world applications.

Conclusion

Deleting data using jQuery AJAX with PHP allows you to create fast and interactive applications.

It improves user experience by removing records instantly without reloading the page.

Once you understand this concept, you can build complete CRUD applications with create, read, update, and delete functionality.

🚀 What to Learn Next?

After learning how to delete data, the next step is:

  • Update data using jQuery AJAX
  • Build complete CRUD applications
  • Add authentication and user roles

👉 Recommended next tutorial:
jQuery AJAX CRUD – Update Data

Related Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *