Wednesday, 27 February 2008

Deleting record with Ajax using prototype.js and PHP

Are you Ajax newbie? This post explains how to remove record from database tables using Ajax and PHP.

My friend William asked to me to write a post for "beginners" about how to use prototype.js framework an PHP to delete a record from a database with Ajax. This is a simple overview with basic features you can use and improve in your web projects.


Tutorial's structure includes three files:

  • index.php (with a list of record you want to delete)
  • delete.php (PHP code to delete records into your database)
  • prototype.js (to enable Ajax)
Step 1: include prototype.js
Download prototype.js and create a new page (index.php). Add this line of code in the <head> tag on index.php to include prototype framework:

<script type=""text/javascript" src="prototype.js"></script>


Step 2: HTML code
Image to have the following code in index.php:

<ul>
<li>Jack Bauer <a href="#" onClick="deleteUser(1)">delete</a></li>
<li>Gregory House <a href="#" onClick="deleteUser(2)"> delete</a></li>
<li&gtFox Mulder <a href="#" onClick="deleteUser(1)">delete</a></li>
</ul>

...a simple list with names and a link to delete the user from the DB. Each link call a JavaScript function deleteUser() with argument the ID (primary key) of the user you want to delete. Database table USER has some attributes and a primary key (id_user_pk). You can generate dinamically this list using a for example a code like this:

<?php
/* Database connection */

include('config.php');
$getUser_sql
= 'SELECT * FROM USER';
$getUser = mysql_query($getUser_sql);
?>
<ul>
<?php while ($row = mysql_fetch_array($getUser)) {?>
<li> <?php echo $row['name']; ?> <a href="#" onClick="deleteUser(<?php echo $row['id_user_pk']; ?>)">delete</a></li>
} ?
>
<>

Take a look here to see an explanation of connection parameters to a MySQL database in config.php.

Step 3: delete.php
Create a new page (delete.php). This page contains a query PHP to delete the record passed in argument from javascript function deleteUser(id):

<?php
/* Database connection */
include('config.php');
if(isset($_POST['user_id'])){
$userID = $_POST['user_id'];
$sql = 'DELETE FROM USER where id_user_pk ="'.$userID.'"';
mysql_query($sql);
} else { echo '0'; }
?>


Step 4: Javascript function deleteUser(id)
This function pass with the method POST to the page delete.php the id of the user you want to delete from the table. Add the following lines of code below the code in step 2:

<script type="text/javascript">
function deleteUser(id){
new Ajax.Request('delete.php', {
parameters: $('idUser'+id).serialize(true),
});
}
</script>


It's all. I hope it's clear :)

No comments:

Post a Comment