PHP is not reloaded automatically after processing - javascript

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
}
}

Related

Passing js variable to php using ajax does not work

I want to get variable rating_idex in my php file so if is user click button #add-review it should pass in ajax variable and it will get array in php file and send review to the database, but it is not working and I don't see solution
$('#add-review').click(function(){
var user_name = $('#reviewer-name').val();
var user_review = $('#review').val();
console.log(user_name);
console.log(rating_index);
console.log(user_review);
if(user_name == '' || user_review == '')
{
alert("Please Fill Both Field");
return false;
}
else
{
$.ajax({
url:"rating-data.php",
method:"GET",
data:{
rating_index: rating_index,
user_name: user_name,
user_review: user_review
},
success:function(data)
{
$('#review_modal').modal('hide');
load_rating_data();
console.log(data);
}
})
}
});
This is my php code when I can get the variable and send them to the database:
<?php
include 'connection.php';
echo ($rating_index);
if(isset($_GET["rating_index"]))
{
$data = array(
':user_name' => $_GET["user_name"],
':user_rating' => $_GET["rating_index"],
':user_review' => $_GET["user_review"],
':datetime' => time()
);
$query = "
INSERT INTO review_table
(user_name, user_rating, user_review, datetime)
VALUES (:user_name, :user_rating, :user_review, :datetime)
";
$query_run = mysqli_query($conn, $query);
if($query_run){
echo "Your Review & Rating Successfully Submitted";
} else{
echo '<script type="text/javascript"> alert("Something went wrong") </script>';
echo mysqli_error($conn);
}
}
?>
When I am trying to echo ($rating_index) it give me feedback that variable does not exist so it is something with ajax but can't find solution, thanks in advance for any solutions
Instead of echo ($rating_index); try echo ($_GET["rating_index"]); reason being you didn't actually declared $rating_index
if I'm not wrong you want to pass the PHP variable in javascript?
if yes you cant pass the PHP variable in js like this.
var x = " < ? php echo"$name" ? >";
you can pass your PHP variable like this but in only the .php file not in the .js

How to get variable value from PHP to Java Script via AJAX?

I have created a chat website. I send the message with AJAX to PHP and the MySql Database. The messages are fetched using AJAX which runs per second. But this lead to fetch of all the messages (from starting to end). I came with an solution that I will pass the last message ID to the AJAX/JAVA SCRIPT and then fetch only the messages which are more than that.
Here is the Java Script / AJAX
function fetchdata(){
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
data : {cuser:cuser, ouser:ouser},
success: function(read){
$("#readarea").html(read);
}
});
}
Here is the PHP code to get messages:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
$result = mysqli_query($conn, $sql) or ("Query Failed");
while($row=mysqli_fetch_assoc($result)){
if($row["fromid"]==$_POST['cuser']){
echo "<div class='cuser'>".$row["message"]."</div>";
}else{
echo "<div class='ouser'>".$row["message"]."</div>";
}
}
Here I want to get the ID (message) in the Java Script function back from the PHP and use it as a variable for fetching the messages which will be more than it.
You should return JSON from the PHP, instead of HTML. That way you can return an object with properties such as ID, message, etc. Then you can use Javascript to store the latest ID, and also to put the message into your page with the relevant HTML.
Something like this:
PHP:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
if (!empty($_POST["lastid"]) $sql .= " AND id > {$_POST['lastid']}";
$result = mysqli_query($conn, $sql) or ("Query Failed");
$messages = array();
while($row=mysqli_fetch_assoc($result)){
$messages[] = $row;
}
echo json_encode($messages);
JS:
//make this global so it persists beyond each call to fetchdata
var lastMessageID = null;
function fetchdata()
{
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
dataType: "json",
data : { cuser: cuser, ouser: ouser, lastid: lastMessageID },
success: function(read) {
for (var i = 0; i < read.length; i++)
{
var className = "ouser";
if (read[i].fromid == cuser) classname = "cuser";
$("#readarea").append("<div class='" + className + "'>" + read[i].message + "</div>");
lastMessageID = read[i].id;
}
}
});
}
P.S. Please also take note of the comment about about SQL injection and fix your query code, urgently. I haven't done it here for the sake of brevity, but it must not be ignored.

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.

parse return data from html to ajax

I have some problem with the returned value of ajax.
this is the ajax code:
$(document).ready(function() {
var request;
$("#flog").submit(function(event) {
if(request)
request.abort();
event.preventDefault();
var form = $(this);
var serializedData = form.serialize();
var btnname = $('#log').attr('name');
var btnval = $('#log').val();
var btn = '&'+btnname+'='+btnval;
serializedData += btn;
request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: serializedData,
});
request.done(function(data, status, jdXHR) {
alert(data);
});
request.fail(function(jdXHR, status, error) {
});
});
});
it takes data from a form and send it to another page.
this is the second page:
<?php include 'head.php'; ?>
<?php
if($_POST['login']) {
session_regenerate_id(true);
$con = mysqli_connect("localhost", "Alessandro", "ciao", "freetime")
or die('Could not connect: ' . mysqli_error($con));
$query = 'SELECT * FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
if(mysqli_num_rows($result) == 0) {
mysqli_close($con);
session_unset();
session_destroy();
$res = false;
return $res;
}
$query = 'SELECT password FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
$line = mysqli_fetch_array($result, MYSQL_ASSOC);
if(md5($_POST['password']) != $line['password']) {
mysqli_close($con);
session_unset();
session_destroy();
return false;
}
?>
<?php include 'foot.php'; ?>
and in .done the returned data is all the html page.
How can I retrieve only a data, like $res? I tried with json_encode() but with no results.
If in the second page I delete the lines include 'head.php' and include 'foot.php' it works. But I need that the secon page is html, too.
Somenone can help me?
Dont use the Data attribute from AJAX.
Replace
request.done(function(data, status, jdXHR) {
alert(data);
});
with
request.done(function(data, status, jdXHR) {
alert(jdXHR.responseText);
});
You could do it in a much simpler way.
In PHP store the result of the attempted login into a variable, for instance $result =0; to start with
If the login is valid change it to 1 and return it to ajax by doing an echo at the end of your PHP file. If you need other value returned such as the name you could add it to the variable with a separator such as || for instance.
in javascript collect your return and go data = data.split('||');
if (data[0] == 0){alert("Welcome back " + data[1]);}else{alert("wrong login...")}
Previous use is correct, you need to escape the user collected in your PHP script.
Hope this helps.

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?

Categories