asynchronous commenting using ajax - javascript

I'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#comment_part").html(html);
window.location.reload();
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
//header("Location:csair.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.

There are 3 main problems in your code:
You are not returning anything from insert.php via ajax.
You don't need to replace the whole comment_part, just add the new comment to it.
Why are you reloading the page? I thought that the whole purpose of using Ajax was to have a dynamic content.
In your ajax:
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
Within insert.php you need to return the new comment html:
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
Please note that you currently don't have any error handling, so when you return die('comment is not set....') it will be displayed as well as a new comment.
You can return a better structured response using json_encode() but that is outside the scope of this question.

You're using jQuery.html() which is replacing everything in your element with your "html" contents. Try using jQuery.append() instead.

Related

Comment System: JavaScript not 'returning' right comment_Id

I am building a basic commenting system for a website: Comments can be made and users can reply on every comment. I am using ajax for submitting and retrieving/displaying the comments and replies. I have successfully coded the comments part, but need assistance on the replies part.
Every comment stored in the database has a unique id (comment_id) associated with it. And I use that id to associate replies to each respective comment.
The form for the comments, which is in index.php:
<div id="showComments"></div> <!--div where comments are inserted by AJAX-->
<div style="text-align:center;">
<form action="" method="post" id="commentForm">
<textarea name="comment" id="comment" rows="1"></textarea><BR>
<button type="submit" name="new_comment" onClick="submitComment()">Comment</button>
</form>
<div id="message"></div> <!--div where a status (comment submitted successfully or failed) is inserted by AJAX-->
</div>
The JavaScript for submitting the comment and displaying the comments, also in index.php.
<script>
$(document).ready(function() {
showComments();
});
function submitComment(){
var commentText = document.getElementById('comment').value;
var commentString = 'comment=' + commentText;
event.preventDefault();
$.ajax({
url: "insert_com.php",
method: "POST",
data: commentString,
dataType: "JSON",
success: function(response) {
if (!response.error) {
$("#commentForm")[0].reset();
$("#message").html(response.message);
showComments();
} else if (response.error) {
$("#message").html(response.message);
}
}
});
}
function showComments() {
$.ajax({
url: "get_com.php",
method: "POST",
success: function(response) {
$("#showComments").html(response);
}
});
}
</script>
The file insert_com.php, which submits the comment to the database, to where AJAX posts in the submitComment() function:
<?php
if(!empty($_POST["comment"])){
$new_com_date = date('Y-m-d H:i:s');
$insertComment = "INSERT INTO comments (text, date) VALUES ('".$_POST["comment"]."', '".$new_com_date."')";
mysqli_query($connect, $insertComment) or die("database error: ". mysqli_error($connect));
$message = '<label>Comment posted Successfully.</label>';
$status = array(
'error' => 0,
'message' => $message
);
} else {
$message = '<label>Error: Comment not posted.</label>';
$status = array(
'error' => 1,
'message' => $message
);
}
echo json_encode($status);
?>
And the file get_com.php, which retrieves and displays the comments but also retrieves the replies and contains the form for submitting the replies
<?php
require 'php/connect.php';
$comment = mysqli_query($connect, "SELECT * FROM `comments` ORDER BY `date` DESC");
$string ="";
foreach($comment as $item) {
$date = new dateTime($item['date']);
$date = date_format($date, 'M j, Y | H:i:s');
$comment = $item['text'];
$comment_id = $item['id'];
$string .= '<div style="text-align:center;">'
.'<div id="'.$comment_id.'" style="text-align:center;">'
.'<span><b>'.$comment.'</b></span>&nbsp'
.'<span><b>'.$date.'</b></span> '
.'<span><b>'.$comment_id.'</b></span>'
.'</div>';
$reply = mysqli_query($connect, "SELECT * FROM `replies` WHERE `comment_id`='$comment_id' ORDER BY `date` DESC");
foreach($reply as $com) {
$reply_date = new dateTime($com['date']);
$reply_date = date_format($reply_date, 'M j, Y | H:i:s');
$reply_com = $com['text'];
$com_id = $com['comment_id'];
$string.= '<div>'
.'<span>'.$reply_com.'</span> '
.'<span class="time">'.$reply_date.'</span> '
.'<span><b>'.$com_id.'</b></span>'
.'</div>';
}
$string .=
'<div>'
.'<form action="" method="post" id="replyForm">'
.'<textarea name="new-reply" id="new-reply" rows="1"></textarea>'
.'<input type="hidden" id="com_id" name="com_id" value="'.$comment_id.'"/>'
.'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply()">Reply</button> '
.'<span><b>'.$comment_id.'</b></span>'
.'</form>'
.'<span id="replymessage"></span>'
.'</div>'
.'</div>'
.'<hr style="width:300px;">';
}
echo $string;
?>
Now, here is where the problem comes in. I want to use AJAX to submit a reply to a particular comment with an id $comment_id. I want to get this id from the hidden input contained in the reply form (The form with id replyForm.
I wrote the following JavaScript to retrieve the id belonging to a particular comment:
<script>
function submitReply(){
var replyText = document.getElementById('new-reply').value; console.log(replyText);
var commId = document.getElementById('com_id').value; console.log(commId);
event.preventDefault();
...
</script>
As you can see, I log the form text (the reply) and the comment id to the console to see whether I am capturing the correct data, but it always returns the id of the last comment submitted. (i.e the reply form works for the last comment. The JavaScript logs the correct text and comment id for a reply on the last comment, but for all other replies it returns the text of the reply on the last comment and the id of the last comment.
I know it's quite a lot of code, so if anyone more experience could assist me it would certainly be appreciated.
You have more than one element with id="com_id". id should be unique. What you can do is when you are generating the DOM in get_com.php, instead of
'<input type="hidden" id="com_id" name="com_id" value="'.$comment_id.'"/>'
'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply()">Reply</button> '
You can call submitReply() with the right ID, like so:
'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply('.$comment_id.')">Reply</button> '
Then, the comment ID would be the argument of your submitReply method and you wouldn't need to read it from the input field.
<script>
function submitReply(commId){
var replyText = document.getElementById('new-reply').value;
console.log(replyText);
console.log(commId);
event.preventDefault();
...
</script>
Your <textarea> has the same issue as well.
I suggest to assign a unique ID to your <textarea> as well, something like "reply-'.$comment_id.'". Then, when submitReply(comment_id) gets called, you know which comment ID is the call for, so you can construct the unique ID for the exact same textarea, and get the value of the desired element.
<script>
function submitReply(commId){
var replyText = document.getElementById('reply-' + commId).value;
console.log(replyText);
console.log(commId);
event.preventDefault();
...
</script>

ajax response is showing javascript and not hidding it

I am building a comment system in which there is features like: delete main post, delete comment, delete reply, edit main post, edit comment, edit reply, Read more/Read less for post that is >250 character. So i am now at the stage of making the edit for reply post to a comment, everything else is working perfectly except this one, when i click i need to see reply post with Read More/Read Less feature, so to make this happen after ajax response i needed to paste the javascript codes for this feature in the php script which edit the reply, so when i make .html(data) i see the javascript codes inside the span which i want the response to be shown ! please help ! i made the same script for comment and same way placing javascript code in the php page that edited the comment but i do not see the javascript lines ! below are pictures that shows what is happening and my script next :
// THIS TAKES CARE OF THE EDIT FEATURE OF THE REPLY ON BOARD_COMMENT PAGE
$(document).on("click", ".board_reply_edit_button", function() {
// this will select the form in which is contained the edit button
var editBoardButtonAttribute = $(this).attr("id");
var editBoardButtonIdArray = editBoardButtonAttribute.split("-");
var editBoardButtonId = editBoardButtonIdArray[0];
$("#"+editBoardButtonId+"-formBoardReplyEdit").toggle();
$("#"+editBoardButtonId+"-spanBoardReplyEdit").toggle();
// if the cancel button is clicked, this happens
$(document).on("click", ".board_cancel_button", function() {
// this will select the form in which is contained the edit button
var cancelBoardAttribute = $(this).attr("id");
var cancelBoardButtonIdArray = cancelBoardAttribute.split("-");
var cancelBoardButtonId = cancelBoardButtonIdArray[0];
$("#"+cancelBoardButtonId+"-formBoardReplyEdit").hide();
$("#"+cancelBoardButtonId+"-spanBoardReplyEdit").show();
});
// if the edit button is clicked we send this ajax call
$(document).on("click", ".board_edit_save_button", function(e) {
e.preventDefault();
// this will select the form in which is contained the edit button
var saveBoardAttribute = $(this).attr("id");
var saveBoardButtonIdArray = saveBoardAttribute.split("-");
var saveBoardButtonId = saveBoardButtonIdArray[0];
var editBoardTextareaVal = $("#"+saveBoardButtonId+"-textareaBoardReplyEdit").val();
url = "widgets/edit_board_comment_reply.php";
if (editBoardTextareaVal === "") {
CustomSending("This post can't be left blank")
setTimeout(function () {
$("#sending_box").fadeOut("Slow");
$("#dialogoverlay").fadeOut("Slow");
}, 2000);
// this makes the scroll feature comes back
setTimeout(function(){
$("body").css("overflow", "auto");
}, 2001);
} else {
$.ajax({
url: url,
method: "POST",
data: {
reply_id: saveBoardButtonId,
board_reply_textarea: editBoardTextareaVal
},
beforeSend: function() {
CustomSending("Sending...");
},
success: function(data){
$("#sending_box").fadeOut("Slow");
$("#dialogoverlay").fadeOut("Slow");
// this makes the scroll feature comes back
$("body").css("overflow", "auto");
$("#"+saveBoardButtonId+"-spanBoardReplyEdit").html(data); //// THIS IS THE KEY LINE
$("#"+saveBoardButtonId+"-formBoardReplyEdit").hide();
$("#"+saveBoardButtonId+"-spanBoardReplyEdit").show();
}
});
}
});
});
this is the edit_board_comment_reply.php file :
<?php
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
if(isset($_POST['reply_id'], $_POST['board_reply_textarea'])) {
$reply_id = (int)$_POST['reply_id'];
$board_reply_textarea = mysql_prep($_POST['board_reply_textarea']);
// INSERT into table
$query = "UPDATE board_comment_reply_table ";
$query .= "SET reply = '$board_reply_textarea' ";
$query .= "WHERE reply_id = $reply_id";
$result = mysqli_query($connection, $query);
// now we select the updated board post
$query2 = "SELECT * FROM board_comment_reply_table ";
$query2 .= "WHERE reply_id = $reply_id ";
$result2 = mysqli_query($connection, $query2);
confirm_query($result2);
$result_array = mysqli_fetch_assoc($result2);
}
echo nl2br($result_array['reply']);
?>
<script>
// This takes care of the board comment Continue Reading feature ---------------------------------------------------------
$(".reply_content_span").each(function(){
var boardReplyPostThis = $(this);
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if(boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
boardReplyPostThis.text(boardPostTextCut+"...");
boardReplyPostThis.append('<a class="board_read_more_link board_reply_read_more" id="'+boardPostId+'-readMoreComment">Read More</a>');
} else {
boardReplyPostThis.text(boardPostText);
}
$("body").on("click", ".board_reply_read_more", function(e){
e.preventDefault();
boardReplyPostThis.text(boardPostText);
boardReplyPostThis.append('<a class="board_read_more_link board_reply_read_less">Read Less</a>');
});
$("body").on("click", ".board_reply_read_less", function(e){
e.preventDefault();
boardReplyPostThis.text(boardPostTextCut+"...");
boardReplyPostThis.append('<a class="board_read_more_link board_reply_read_more">Read More</a>');
});
});
</script>
This is the html code :
<span class="comment_content_span" id="<?php echo $board_comment_id_number;?>-spanBoardCommentEdit"><?php echo nl2br($board_comment_text);?></span>
<form action="" method="post" class="board_comment_edit_form" id="<?php echo $board_comment_id_number;?>-formBoardCommentEdit">
<textarea rows="2" name="board_comment_edit_textarea" class="board_comment_edit_textarea" id="<?php echo $board_comment_id_number;?>-textareaBoardEdit"><?php echo $board_comment_text;?></textarea>
<input type="submit" value="Edit" class="board_edit_save_button" id="<?php echo $board_comment_id_number;?>-saveBoardCommentEdit"/>
<input type="button" value="Cancel" class="board_cancel_button" id="<?php echo $board_comment_id_number;?>-cancelBoardCommentEdit"/>
</form>
Solution found !
instead of the javascript between the script tags, I added this line in the edit_board_comment_reply.php
<script src="js/board.js"></script>
It seems that the appended javascript exitsts in "data" which is send back from your php script. First of all you should try to define the "dataType" property of your ajax-post because the output is preprocessed by jquery depending on that property.
After that you can try to grab just the content-division from your resonse-html and append that instead of the whole result.
For example like this $(body).append($(data).find('#contentID')).

AJAX request to fill a popover working only once to a php file

I have made a simple search bar in which on every .keyup() event,an asynchronous request goes to a php file which then fills the data in the bootstrap popover.
The problem is that in the popover,the data is filled only once,i.e.,when I type the first character,after that the same data is shown even after multiple .keyup() events.
Here is the code:
HTML:
<input type="text" data-placement="bottom" id="search" name="search1" class="search-box" placeholder="Search..." title="Results"/>
AJAX:
$("#search").keyup(function(){
console.log('erer');
//var searchString = $("#search").val();
var data = $("#search").val();
console.log(data);
var e=$(this);
//if(searchString) {
$.ajax({
type: "POST",
url: "do_search.php",
data: {search:data},
success: function(data, status, jqXHR){
console.log('html->'+data+'status->'+status+'jqXHR->'+jqXHR);
e.popover({
html: true,
content: data,
}).popover('show');
},
error: function() {
alert('Error occured');
}
});
//}
});``
PHP:
$word = $_POST['search'];
//echo $word;
//$word=htmlentities($word)
$sql = "SELECT FName FROM user WHERE FName LIKE '%$word%' ";
//echo $sql;
// get results
//$sql = 'SELECT * FROM Profiles';
$end_result = '';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
#$end_result.='<li>'.$row["FName"].'</li>';
#$_SESSION['fnamer'] = $row['Fname'];
#$end_result.='<li>'.'<a href =view_search.php>'.$row["Fname"].'</a>'.'</li>';
echo '<a href =view_search.php>'.$row["FName"].'</a>';
}
#echo $end_result;
}
Even though in the success parameter of the $.ajax,the data is being printed fine,i.e.,it changes as I enter different alphabets,but the popover content does not change.
Please provide some suggestions to resolve this problem.
The popover is already shown. This is not the correct way of changing the popover content dynamically.
Your code: https://jsfiddle.net/gsffhLbn/
Instead, address the content of the popover directly:
var popover = e.attr('data-content',data);
popover.setContent();
Working solution
Fiddle: https://jsfiddle.net/gsffhLbn/1/

Using ajax to display new database inputs without refreshing the page

I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?

PHP is not reloaded automatically after processing

Hi I have a PHP file with data. The value is passed on to another php file which process it successfully. But the first php file does not refresh to update the new result. It have to do it manually. Can any one tell me where I'm wrong or what needs to be done. Please find my code below.
PHP code (1st page, index.php)
function display_tasks_from_table() //Displayes existing tasks from table
{
$conn = open_database_connection();
$sql = 'SELECT id, name FROM todolist';
mysql_select_db('todolist'); //Choosing the db is paramount
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo "<form class='showexistingtasks' name='showexistingtasks' action='remove_task.php' method='post' >";
while($row = mysql_fetch_assoc($retval))
{
echo "<input class='checkbox' type='checkbox' name='checkboxes{$row['id']}' value='{$row['name']}' onclick='respToChkbox()' >{$row['name']} <img src='images/show_options.gif' /><br>";
}
echo "</form>";
echo "<label id='removeerrormsg'></label>";
close_database_connection($conn);
}
Javascript code which finds the selected value:
var selVal; //global variable
function respToChkbox()
{
var inputElements = document.getElementsByTagName('input'),
input_len = inputElements.length;
for (var i = 0; i<input_len; i++)
{
if (inputElements[i].checked === true)
{
selVal = inputElements[i].value;
}
}
}
jQuery code which passes value to another page (remove_Task.php):
$(document).ready(function() {
$(".checkbox").click(function(){
$.ajax({
type: "POST",
url: "remove_task.php", //This is the current doc
data: {sel:selVal, remsubmit:"1"},
success: function(data){
//alert(selVal);
//console.log(data);
}
});
});
});
PHP code (2nd page, remove_task.php);
session_start();
error_reporting(E_ALL);ini_set('display_errors', 'On');
$task_to_remove = $_POST['sel'];
function remove_from_list() //Removes a selected task from DB
{
$db_connection = open_database_connection();
global $task_to_remove;
mysql_select_db('todolist');
$sql = "DELETE FROM todolist WHERE name = "."'".$task_to_remove."'";
if($task_to_remove!='' || $task_to_remove!=null)
{
mysql_query($sql, $db_connection);
}
close_database_connection($db_connection);
header("Location: index.php");
}
if($task_to_remove != "") {
remove_from_list();
}
The selected value is getting deleted but the display on index.php is not updated automatically. I have to manually refresh to see the updated result. Any help would be appreciated.
By calling header("Location: index.php"); you don't redirect main page. You sent an ajax request - you can think about it as of opening a new page at the background, so this code redirects that page to index.php.
The better way to solve your task is to return status to your success function and remove items which were deleted from the database.
success: function(data){
if(data.success){
//remove deleted items
}
}

Categories