Tuesday, April 9, 2013

Delete row with jQuery and PHP

Do you want to delete a row in HTML and MySQL table with fancy fade out effect? This is the right tutorial for you assuming that you are familiar with basics of jQuery and PHP.
You make an asynchronous call to PHP script called delete.php so end user doesn't leave page when a row is deleted, instead he gets an alert box that confirms that row is deleted and the row gradually disappears.

First create a table with two columns id and name. Create file index.php with following code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Delete row with jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $("a[id^='delete']").click(function() {
  var numrow = $(this).attr("id");
  numrow = numrow.substr(6);
   $.ajax({
    type: 'POST',
    url: 'delete.php',
    data: { id: numrow },
    error: function() {
       alert('Error!');
    },
    success: function(data) {
       alert('Broker number '+data+' is deleted.');
        numrow = "#row"+numrow;
     $(numrow).fadeOut();
    }
   });
 });
});
</script>
</head>
<body>
<?php
require("connect_to_database.inc");
$sql = new MySQLi($hostname, $username, $password, $database);
if (mysqli_connect_errno()) {
 printf("Connect failed: %s\n", mysqli_connect_error());
 exit();
}
$res = $sql->query("SELECT * FROM brokers");

while ( $row = $res->fetch_assoc() )
{
 $r = $row['id'];
 echo "<div style='border:dotted;background:lightgray;' id='row$r'>{$row['name']} <a href='#' id='delete$r'>Delete broker</a></div><br/>\n";
}
$res->close();
$sql->close();
?>
</body>
</html>
And in the same folder create file named delete.php:
<?php
$prom = $_POST['id'];
require("connect_to_database.inc");
$sql = new MySQLi($hostname, $username, $password, $database);
if (mysqli_connect_errno()) {
 printf("Connect failed: %s\n", mysqli_connect_error());
 exit();
}

 $prom = $_POST['id'];
 $res = $sql->query("DELETE FROM brokers WHERE id = $prom");
 if($res == FALSE) {
  $res->close();
  $sql->close();
  die('Error in delete.php!');
 }
 echo $prom;
?>
If everything goes OK this page will never be shown to end user. Don't forget to add path to your file with parameters for server, database, username and password.

You need to be familiar with jQuery attribute selector and ajax function.

No comments:

Post a Comment