Here is a quick tip on on building an ajax delete page in php and mysql with a bit of jQuery to handle the ajax. We will assume you have some list of entries in a database and that you would like to remove them without the page reloading. We will also give the user a confirmation before they delete but it will not be an ugly alert box, woot! Those boxes are so web 1.0.
First, we will be using one jQuery plugin to handle the confirmation. Second we will use some code and techniques from David Walsh.
jQuery Confirm Plugin will allow use to present the user a warning before the item is removed. I will use the default configuration for simplicity but there are some options you can tweak depending on your preferences.
Now below is the first part of the JavaScript that we will add to the head. You notice around line 27 that starts with “$(‘.delete’).confirm({” does two things.
First it present a warning message to the user.
Second there is a timeout feature which will allow for the message to be removed and turn back to the normal state of the page.
Once the user has confirmed the or clicked “Yes” in the $(‘.delete’).click(function() { (starts on line 9 below) will kick in and then remove the entry via an ajax call. All we did was add a class of .delete to the entry and then the id will need to be the corresponding id field in your mysql database. More on that below.
Add this to your head of your html document.
Sample html
| Name | Category | Contact Last Name | Contact First Name | ||
|---|---|---|---|---|---|
| Business 1 | Auto Services | First Name | Last Name | ||
| Business 2 | Accountants & Tax Services | First Name | Last Name | ||
| Business 3 | Advertising , Creative, & Marketing Services | First Name | Last Name |
Now we will need the php to delete the item. This would be the delete.php as shown above in the javascript that is within the head section.
// you will need your database connection string here
if(isset($_GET['delete']))
{
$query = 'DELETE FROM my_table WHERE item_id = '.(int)$_GET['delete'];
$result = mysql_query($query,$link);
}
So once the user clicks on yes to confirm the delete the ajax request is made to the server and delete.php is fired where it removes the entry from the database. Finally upon a successful removal of the record in the database we remove the row containing the entry from the users screen.