I am creating a forum in which the posted user has option to delete his own posts. So, I am using ajax to send get request to delete a particular post and I am echoing null in place of the deleted post. The problem here is the post is getting deleted but the page is reloading after deletion which shouldn't happen as I am using ajax request. Can anyone help?
PHP CODE TO DISPLAY THE POSTS(ONLY A PART)
$sql = "SELECT * FROM classposts where branch='$branch' and joindate='$year' and class='$class' order by".$orderby." desc";
$result = $connection->query($sql);
if(isset($_SESSION['username'])){
$username=$_SESSION['username'];
}
while($row = $result->fetch_assoc()) {
echo "<span id='postspan".$row['id']."' name='postspan".$row['id']."' >";
echo "<span id='editspan".$row['id']."' name='editspan".$row['id']."' >";
echo "-----------------------------------</br>";
echo "-----------------------------------</br>";
echo "Posted By: ".$row['user']."    ";
if($username==$row['user']){
echo "<a href='classwall.php' onclick='deletepost(".$row['id'].")' >DELETE POST</a>   ";
}
Ignore if any parenthesis are not matching as this is only a part of the code.
javascript function which is called after delete link is clicked
function deletepost(postid){
var r=confirm("Are you sure you want to delete the post?");
if(r==true){
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("postspan"+postid).innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","deletepost.php?pid="+postid,true);
xmlhttp.send();
}else{}
}
deletepost.php page
$pid=$_GET['pid'];
$query="delete from dubiousposts where id='$pid'";
$sql=mysqli_query($connection,$query);
$query="delete from genuineposts where id='$pid'";
$sql=mysqli_query($connection,$query);
$query="delete from posts where id='$pid'";
$sql=mysqli_query($connection,$query);
if($result=mysqli_fetch_array($sql)){
echo "";
}