<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",开发者_如何学C
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
</script>
<?php
include('config.php');
$sql=mysql_query("SELECT * FROM messages ORDER BY mes_id DESC LIMIT 20");
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg'];
?>
<div id="<?php echo $msgID; ?>" align="left" class="message_box" >
<span class="number"><?php echo $msgID; ?></span><?php echo $msg; ?>
<a href="delete.php" class="delete">x</a>
</div>
<?php
}
?>
I have coded this to show entries from database and a delete button to show in every div. delete.php includes code
<?php
include('config.php');
echo $id=$_REQUEST['msgID'];
$sql="delete from messages where mes_id='$id'";
$res=mysql_query($sql) or die(mysql_error());
?>
but it is not working. I am not able to delete entry from database..
check your request var_dump($_REQUEST)
you send var string = 'id='+ id ;
and trying to receive $_REQUEST['msgID']
just change to $_REQUEST['id']
At first glance, I think you want to change this line:
var id = $(this).attr("id");
Into:
var id = $(commentContainer).attr("id");
Because this
refers to the clicked link, which does not have an id
attribute.
In delete.php
you are looking for $_REQUEST['msgID']
but you are using id
(not msgID
) when you post the request, so you will need to change that to match as well.
In addition to Subdiggers answer, nice potential for SQL Injection, see: http://php.net/manual/en/security.database.sql-injection.php
Your data is wrong: instead of:
data: string,
Where string is:
var string = 'id='+ id ;
Data should be in Key/Value pairs. so:
data: msgID : id
I made it into msgID because your $_REQUEST['msgID']
is calling msgID.
Watch out for SQL injections! Use intval on $id before inserting it into your query, to make sure it's an integer.
精彩评论