The purpose of the script below is to allow users to post new updates and to delete them without the page refreshing : that's why i'm using AJAX.
There are 2 glitches:
when a user posts an update, it's correctly saved in the DB, and the correct update slides down in my table but when i look at the source code, i can see the wrong postid is echoed (it's always the postid from a couple rows below in the DB).
when a user deletes a post, nothing happens on the frontend: tr doesn't slide up BUT the row does get deleted correctly in the DB.
PHP part :
echo "<table id=\"update_list\">
<tr class=\"cell$postid\">
<td>$post
<div id=\"delete\">
<span class=\"delete_update\"><a href=\"#\" id=\"$postid;\">X</a></span>
</div>
<hr>
</td>
</tr>
</table>";
AJAX part:
<script type="text/javascript">
$(function() {
$("#addpost_button").click(function()
{
var element = $(this);
var boxval = $("#status").val(); // #status is the ID of the input where the users type in updates
var dataString = 'post='+ boxval;
if(boxval=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$.ajax({
type: "POST",
url: "update_post.php",
data: dataString,
cache: false,
success: function(html){
$("#cell").prepend(html);
$("#update_list tr:first").slideDown("slow");
document.getElementById('post').value='';
$("#flash").hide();
}
});
}
return false;
});
$('.delete_update').live("click",function()
{
var ID = $(this).attr("id");
var dataString = 'postid='+ ID;
if(confirm("Sure you want to delete this post? "))
{
$.ajax({
type: "POST",
url: "delete_post.php",
data: dataString,
cache: false,
success: function(html){
$(".cell"+ ID).slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});
</script>
Any help will be much appreciated!
EDIT: Code from update_post.php:
<?php
include "includes/config.php";
if(isset($_POST['post']))
$table=query("INSERT INTO postlist (id, postid, post) VALUES (?, ?, ?)",
$_SESSION["id"], '', $_POST["post"]);
$table = query("SELECT post, postid FROM postlist WHERE id = ? ORDER BY postid DESC",
$_SESSION["id"]);
foreach ($table as $row){
$post=$_POST['post'];
$postid = $row["postid"];
echo "<table id=\"update_list\">
<tr class=\"cell$postid\">
<td>$post
<div id=\"delete\">
<span class=\"delete_update\"><a href=\"#\" id=\"$postid;\">X</a></span>
</div>
<hr>
</td>
</tr>
</table>";
}
?>