Ajax – mysql Example 1 : Xóa 1 cột dữ liệu với Ajax
Database Table Code
A simple database table two columns msg_id and message.
CREATE TABLE updates(
msg_id INT PRIMARY KEY AUTO_INCREMENT,
message TEXT);
delete_random.php
Contains PHP code displaying records from database. Take a look at class="delete_button"
<ol class="update">
<?php
include("dbconfig.php");
$sql="select * from updates order by msg_id desc";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
$message=stripslashes($row["message"]);
$msg_id=$row["msg_id"];
?>
<li>
<?php echo $message; ?>
< a href="#" id="<?php echo $msg_id; ?>" class="delete_button">X</a>
</li>
<?php
}
?>
</ol>
jQuery code
Contains javascipt code. $(".delete_button").click(function(){}- delete_button is the class name of anchor tag (X). Using element.attr("id") calling delete button value. If id value is even number if(id(even) % 2) = If(0) false
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$(".delete_button").click(function() {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "deleteajax.php",
data: dataString,
cache: false,
success: function()
{
if(id % 2)
{
parent.fadeOut('slow', function() {$(this).remove();});
}
else
{
parent.slideUp('slow', function() {$(this).remove();});
}
}
});
return false;
});
});
</script>
deleteajax.php
Contains PHP code. Delete record from the database.
<?php
include("dbconfig.php");
if($_POST['id'])
{
$id=$_POST['id'];
$id = mysql_escape_String($id);
$sql = "delete from updates where msg_id='$id'";
mysql_query( $sql);
}
?>
CSS Code
*{margin:0;padding:0;}
ol.update
{
list-style:none;font-size:1.2em;
}
ol.update li
{
height:50px; border-bottom:#dedede dashed 1px;
}
ol.update li:first-child
{
border-top:#dedede dashed 1px; height:50px;
}
#main
{
width:500px; margin-top:20px; margin-left:100px;
font-family:"Trebuchet MS";
}
.delete_button
{
margin-left:10px;
font-weight:bold;
float:right;
}