Check/Set button status on page load - javascript

I am using a custom mvc framework and have added a favourite button. Once pressed this displays a 'successfully added to favourites' div, when clicked again it displays a 'successfully removed from favourites' div.
My query works fine, adding and deleting from my favourite table as it should.
What I would like to do now is change the state of the button depending on the selection. For example, if the user has the book in their favourites add btn-success class, if the user hasn't, use the btn-default class.
I'm not sure the best way to approach this. I'm new to php and js so any advice or direction is appreciated. I have tried adding toggleClass to my JS but it's not working. Do I need to perform a query/check on pageLoad?
I have included my code below for reference.
itemView.php
echo
'<td>
<button id="fav" value="'.$book->id.'" type="button" class="btn btn-default"></button>
</td>';
JS (in itemView.php)
$(document).ready(function(){
$( "#fav" ).click(function(){
book_id = $(fav).val();
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>books/checkFav',
data: {book_id:book_id},
success: function () {
window.location.reload(true);
$("#fav").addClass( "btn-success" );
}//end success
});//end ajax
});
});
my checkFav function
public function checkFav($bookid,$userid)
{
$bookid=$_REQUEST['book_id'];
$userid=$_SESSION['user_id'];
$sql = "SELECT * FROM favourite WHERE book_id = :book_id AND user_id = :user_id";
$query = $this->db->prepare($sql);
$query->bindParam(':user_id', $userid);
$query->bindParam(':book_id', $bookid);
$query->execute();
$rows_found = $query->fetchColumn();
if(empty($rows_found)) {
$sql = "INSERT INTO favourite (book_id, user_id) VALUES (:book_id, :user_id)";
$query = $this->db->prepare($sql);
$query->bindParam(':user_id', $userid);
$query->bindParam(':book_id', $bookid);
$query->execute();
if ($query->rowCount() == 1) {
// successful add to favs
$_SESSION["feedback_positive"][] = FEEDBACK_ADDED_TO_FAVS;
return true;
}
} else {
$sql = "DELETE FROM favourite WHERE book_id = :book_id AND user_id = :user_id";
$query = $this->db->prepare($sql);
$query->bindParam(':user_id', $userid);
$query->bindParam(':book_id', $bookid);
$query->execute();
if ($query->rowCount() > 0) {
// successful remove from favs
$_SESSION["feedback_negative"][] = FEEDBACK_REMOVED_FROM_FAVS;
return true;
}
}
}

Use session variable in the ajax request script and using that session variable in page where button exist you can play with button css. for example:
Put this code where Button exists.
$css = "btn_default";
if($_SESSION['btnClicked'] == "success") {
$css = "btn_success";
}
Use $css variable in the button class like--
<button id="fav" value="'.$book->id.'" type="button" class="btn <?php echo $css?>"></button>
This session will manage in the ajax script where in you are adding and deleting favourite.
set session value
$_SESSION['btnClicked'] = 'success'
below the line
$_SESSION["feedback_positive"][] = FEEDBACK_ADDED_TO_FAVS;
and unset the session
unset($_SESSION['btnClicked']);
after the line.
$_SESSION["feedback_negative"][] = FEEDBACK_REMOVED_FROM_FAVS;

Related

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')).

How to get jquery POST request from indirect Page?

I have been working on Like and Unlike feature with jQuery, AJAX and PHP. I am getting jQuery post request from indirect page. For example I have 2 PHP pages, viewProfile.php and LikeMail.php. LikeMail.php is being called by AJAX function in viewProfile.php.
Here is Section of viewProfile.php page's description
-----------------
| Like/Unlike |
-----------------
Here is button which actually comes from LikeMail.php by this AJAX function:
function like()
{
var req = new XMLHttpRequest();
req.onreadystatechange = function()
{
if(req.readyState==4 && req.status==200)
{
document.getElementById('like1').innerHTML=req.responseText;
}
}
req.open('POST','LikeMail.php','true');
req.send();
}
setInterval(function(){like()},1000);
HTML:
<div id="like1"></div>
Output is being shown here in this div. Button above may be Like or Unlike depends on the condition in LikeMail.php which will be described below in LikeMail.php description section.
When one of them (buttons) Like or Unlike is clicked. It then calls respective jQuery click function which sends post request to LikeMail.php.I have mentioned Indirect page in title because Like or Unlike buttons actually exists in LikeMail.php page. But due to AJAX call these buttons are being shown in viewProfile.php page. So I then send post requests through viewProfile.php to actual page LikeMail.phpIt is jQuery post for Unlike button
$(document).ready(function(){
$('#Unlike').unbind().click(function(){
$.post("LikeMail.php",
{Unlike: this.id},
function(data){
$('#response').html(data);
}
);
});
});
It is jQuery post or Like button
$(document).ready(function(){
$('#Like').unbind().click(function(){
$.post("LikeMail.php",
{Like: this.id},
function(data){
$('#response').html(data);
}
);
});
});
End of description section of viewProfile.php page
Here is Section of LikeMail.php page's description
Like or Unlike button is shown in viewProfile.php page depends upon this code:
$check_for_likes = mysqli_query($conn, "SELECT * FROM liked WHERE user1='$user1' AND user2='$user2'");
$numrows_likes = mysqli_num_rows($check_for_likes);
if (false == $numrows_likes) {
echo mysqli_error($conn);
}
if ($numrows_likes >= 1) {
echo '<input type="submit" name="Unlike" value="Unlike" id="Unlike" class="btn btn-lg btn-info edit">';
}
elseif ($numrows_likes == 0) {
echo '<input type="submit" name="Like" value="Like" id="Like" class="btn btn-lg btn-info edit">';
}
Button depends upon these two above conditions.
Now when Like button is clicked, post request from viewProfile.php comes here.
if(isset($_POST['Like'])) //When Like button in viewProfile.php is clicked then this peace of code inside if condition should run and insert some record in database
{
$total_likes = $total_likes+1;
$like = mysqli_query($conn, "UPDATE user SET user_Likes = '$total_likes' WHERE user_id = '$user2'");
$user_likes = mysqli_query($conn, "INSERT INTO liked (user1,user2) VALUES ('$user1','$user2')");
$query3 = "INSERT INTO notification (user1, user2, alert, notificationType) VALUE ('$user1','$user2','unchecked','like')";
if (mysqli_query($conn, $query3)) {
echo "Like";
} else {
echo mysqli_error($conn);
}
}
Similarly when Unlike button is clicked. This peace of code should run.
if(isset($_POST['Unlike'])) //This is the condition for Unlike button. It should delete record from databse
{
$total_likes = $total_likes-2;
$like = mysqli_query($conn, "UPDATE user SET user_Likes='$total_likes' WHERE user_id='$user2'");
$remove_user = mysqli_query($conn, "DELETE FROM liked WHERE user1='$user1' AND user2='$user2'");
$query3 = "DELETE FROM notification WHERE user1='$user1' AND user2='$user2' AND notificationType='like'";
$check = mysqli_query($conn, $query3);
if ($check) {
echo "Unlike";
} else {
echo mysqli_error($conn);
}
}
Problem:
Main problem is that jQuery post request is not being sent from viewProfile.php to LikeMail.php. Is there any way to send jQuery post request from indirect page?

asynchronous commenting using ajax

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.

how to send record to table after click the js link/button?

i want to make an like-unlike button below the post. registered user can give like. i have make the button, but i don't have idea how to send a record when user click the button. i guess i need like table, so this below is table and it field that i have :
user : id_user, username
posting : id_post, id_user, content
like : id_like, id_user, id_post
posting page and like button script :
<?php
include "database_connection.php";
$query=$dbc->query("select user.username, posting.content FROM posting inner join user on user.id_user = posting.id_user where id_post='$_GET[id]'");
$array= $query->fetch_array()
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="post.js"></script>
</head>
<body>
<?php echo $array['username'];?>
<?php echo $array['content'];?>
<!--THIS IS LIKE BUTTON-->
<a class="like-button" href="#"><i class="fa fa-thumbs-up"></i></a>
<!--LIKE BUTTON END-->
</body>
</html>
post.js
$(function() {
$('.like-button').click(function(){
var obj = $(this);
if( obj.data('liked') ){
obj.data('liked', false);
obj.html('<i class="fa fa-thumbs-up"></i>');
}
else{
obj.data('liked', true);
obj.html('<i class="fa fa-thumbs-down"></i>');
}
});
});
Alright, so I've taken the time to create a basic working example for you.
I've included the workings of post.js in an inline script rather than a separate file for simplicity with including a PHP variable inside of the script.
Your HTML Page
<?php
include "database-connection.php";
$user = 1;// get your accessing user ID (not user id of poster)
$post = $_GET['id'];
// query checks whether user has liked the post or not and returns it as well
$query=$dbc->prepare("
SELECT `user`.`username`, `posting`.`content`, IFNULL(`like`.`id_like`,0) AS `id_like`
FROM `posting`
INNER JOIN `user` ON `user`.`id_user` = `posting`.`id_user`
LEFT JOIN `like` ON `like`.`id_user` = ? AND `like`.`id_post` = ?
WHERE `posting`.`id_post`=?");
// bind the parameters to avoid injection
$query->execute(array($user, $post, $post));
$array= $query->fetch(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script type="text/javascript">
// previously post.js
$(function() {
$('.like-button').click(function(e){
e.preventDefault();
var obj = $(this);
// ajax query that returns a JSON object with the result of the request
$.getJSON('likes.php',{post:obj.data('post'), user: <?php echo $user; ?>}, function(data){
//console.log(data); // uncomment for debugging
if(data.error){
// query returned error, handle it however you want
} else {
if (data.like == 1){ // user now likes the post
obj.html('<i class="fa fa-thumbs-up"></i>');
} else { // user now doesn't like the post
obj.html('<i class="fa fa-thumbs-down"></i>');
}
}
});
});
});
</script>
</head>
<body>
<?php echo $array['username'];?>
<?php echo $array['content'];?>
<!--THIS IS LIKE BUTTON-->
<?php
if ($array['id_like']==0){
// user hasn't liked the post, show thumbs down
echo '<a class="like-button" href="#" data-post="'.$post.'"><i class="fa fa-thumbs-down"></i></a>';
} else {
// user has liked the post, show thumbs up
echo '<a class="like-button" href="#" data-post="'.$post.'"><i class="fa fa-thumbs-up"></i></a>';
}
?>
<!--LIKE BUTTON END-->
</body>
</html>
likes.php (the PHP script)
<?php
include "database-connection.php";
$post = $_GET['post'];
$user = $_GET['user'];
$result = (object) ['like'=>null, 'post'=>$post, 'user'=>$user];
$q = $dbc->prepare("SELECT id_like FROM `like` WHERE id_post=? AND id_user=?");
$q->execute(array($post, $user));
$r = $q->fetch(PDO::FETCH_OBJ);
if ($q->rowCount() > 0){
$like = $r->id_like;
} else {
$like = 0;
}
if ($like == 1){
// user likes post, so we unlike it by setting id_like to 0 (for false)
$like = 0;
$u = $dbc->prepare("UPDATE `like` SET id_like = 0 WHERE id_post=? AND id_user=?");
} elseif ($q->rowCount()>0) {
// update because the record exists
$like = 1;
$u = $dbc->prepare("UPDATE `like` SET id_like = 1 WHERE id_post=? AND id_user=?");
} else {
// create the record because it doesn't exist yet
$like = 1;
$u = $dbc->prepare("INSERT INTO `like` (id_like, id_post, id_user) VALUES(1, ?, ?)");
}
if($u->execute(array($post, $user))){
// update succeeded
$result->like = $like;
} else{
// there was an error
$result->error = 'failed to execute in database';
}
// return the json object to your page
echo json_encode($result);
Again, this is just the basics of how this would work. You will have to research logins, sessions, and security for yourself to manage the user who are accessing, posting, and liking the content. But I hope this helps!
Send the request to PHP page on click of like button and handle it there to update the database.
You will need to send an Ajax request to the server and then handle in in a PHP script.
Here's a way to do that.
post.js:
$(function() {
$('.like-button').click(function(){
var obj = $(this);
if( obj.data('liked') ){
obj.data('liked', false);
obj.html('<i class="fa fa-thumbs-up"></i>');
}
else{
obj.data('liked', true);
obj.html('<i class="fa fa-thumbs-down"></i>');
}
$.post('url/to/your_script.php', {
action: 'updateLikeStatus',
status: obj.data('liked'),
post_id: obj.data('id') // ID of the object that user "liked"
});
});
});
You can read more about jQuery.post() here. And here's documentation on more general jQuery.ajax() method.
your_script.php (script that deals with Ajax requests) might look something like this:
<?php
include "database_connection.php";
if (isset($_POST['action']) && $_POST['action'] === 'updateLikeStatus') {
$id_user = $_SESSION['user_id'];
$id_post = $_POST['post_id'];
if ($_POST['status'] === true) {
// adding "like"
$query = $dbc->query("
INSERT INTO like
(id_user, id_post)
VALUES ({$id_user}, {$id_post});
");
$query->query();
} else {
// removing "like"
$query = $dbc->query("
DELETE FROM like
WHERE id_user = {$id_user}
AND id_post = {$id_post};
");
$query->query();
}
}
Note that this code is just an example, you shouldn't use it directly in the production. For one thing, you can't put variables from $_POST directly into a MySQL query, because it will create an SQL Injection type vulnerability, allowing people to perform arbitrary queries on your server. One way to avoid it is by using prepared statements.
Another problem is that you will need to deal with the user authentication and authorization. I've used $_SESSION['user_id'] in my example, but it won't work unless you initialize session and populate user_id value first. Sessions are required so that one user can't like posts on behalf of another user. You can read more about sessions here.

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