AJAX Requests Causing Timeouts - javascript

I am not very proficient with AJAX requests, but I have this simple script in my header:
function refresh_div() {
jQuery.ajax({
url:'progress.php?game=<?php echo $gamename; ?>',
type:'POST',
success:function(results) {
jQuery(".middle").html(results);
}
});
}
t = setInterval(refresh_div,1000);
and then in the progress.php file I have quite a few mysql requests from my db, the purpose of which is to refresh the page with this php data every second. This works fine most times, but what I am finding however is that whenever I call this script a few times back to back simultaneously, I am getting timeout errors and the page wont load. This is all for a browser based game which includes a timer which counts down every second so it is important I find something that will be stable executing php requests every second.
Added progress.php:
<?php
session_start();
$username = $_SESSION["username"];
$gamename = $_GET['game'];
require "../connections/games.php";
$newgamesql = "SELECT * FROM gamelist WHERE name = '$gamename'";
$newgamequery = mysql_query($newgamesql, $gamesdbhandle);
$newgamecount = mysql_num_rows($newgamequery);
$gamenamenospaces = str_replace(' ','_', $gamename);
$gamestatus = mysql_result($newgamequery, 0, 'status');
$numberofplayers = mysql_result($newgamequery, 0, 'numberofplayers');
$player1 = mysql_result($newgamequery, 0, 'player1');
$player2 = mysql_result($newgamequery, 0, 'player2');
$player3 = mysql_result($newgamequery, 0, 'player3');
$player4 = mysql_result($newgamequery, 0, 'player4');
$player5 = mysql_result($newgamequery, 0, 'player5');
$player6 = mysql_result($newgamequery, 0, 'player6');
$player7 = mysql_result($newgamequery, 0, 'player7');
$player8 = mysql_result($newgamequery, 0, 'player8');
$rounds = mysql_result($newgamequery, 0, 'rounds');
$currentround = mysql_result($newgamequery, 0, 'currentround');
$gametimestamp = mysql_result($newgamequery, 0, 'actualtime');
$headmaster = mysql_result($newgamequery, 0, 'headmaster');
$roundtime = mysql_result($newgamequery, 0, 'time');
$activeplayers = mysql_result($newgamequery, 0, 'activeplayers');
$numberofplayers = mysql_result($newgamequery, 0, 'numberofplayers');
$roundtimeproper = strtotime("H:i:s" , $roundtime);
//Round time conversion goes here:
//The specific table query for the individual rounds
$thegamesql = "SELECT * FROM `$gamenamenospaces` WHERE id='$currentround' LIMIT 1";
$thegamequery = mysql_query($thegamesql, $gamesdbhandle);
$echocurrentround = mysql_num_rows($thegamequery) + 1;
$thisroundplayer1 = mysql_result($thegamequery, 0, "player1card");
$thisroundplayer2 = mysql_result($thegamequery, 0, "player2card");
$thisroundplayer3 = mysql_result($thegamequery, 0, "player3card");
$thisroundplayer4 = mysql_result($thegamequery, 0, "player4card");
$thisroundplayer5 = mysql_result($thegamequery, 0, "player5card");
$thisroundplayer6 = mysql_result($thegamequery, 0, "player6card");
$thisroundplayer7 = mysql_result($thegamequery, 0, "player7card");
$thisroundplayer8 = mysql_result($thegamequery, 0, "player8card");
$thisroundwhitecard = mysql_result($thegamequery, 0, "whitecard");
$thisroundwhitecard = str_replace("_", "_____", $thisroundwhitecard);
$thisroundtime = mysql_result($thegamequery, 0, "timestamp");
$now = new DateTime();
$target = DateTime::createFromFormat('H:i:s', $gametimestamp);
$difference = $now->diff($target);
$difference = $difference->format("%I:%S");
//Display the timer
echo '<div id="timer">';
echo 'TIME:';
echo '<br />';
echo $difference;
echo '</div>';
//echo $timer;
//State which round
echo '<div id="toptitle">';
echo $gamename;
echo ' - ';
echo 'Round ';
echo $currentround;
echo '</div>';
if ($gamestatus == 'active') {
//Game is live, display things
echo '<div id="placeholderplaceholder">';
//The card submit bar
if (!empty($player1)) {
if (!empty($player1card)) {
echo '<div class="blackcardplaceholderplaced">';
}else{
echo '<div class="blackcardplaceholder">';
}
echo 'P1';
echo '</div>';
}
if (!empty($player2)) {
if (!empty($player2card)) {
echo '<div class="blackcardplaceholderplaced">';
}else{
echo '<div class="blackcardplaceholder">';
}
echo 'P2';
echo '</div>';
}
if (!empty($player3)) {
if (!empty($player3card)) {
echo '<div class="blackcardplaceholderplaced">';
}else{
echo '<div class="blackcardplaceholder">';
}
echo 'P3';
echo '</div>';
}
if (!empty($player4)) {
if (!empty($player4card)) {
echo '<div class="blackcardplaceholderplaced">';
}else{
echo '<div class="blackcardplaceholder">';
}
echo 'P4';
echo '</div>';
}
if (!empty($player5)) {
if (!empty($player5card)) {
echo '<div class="blackcardplaceholderplaced">';
}else{
echo '<div class="blackcardplaceholder">';
}
echo 'P5';
echo '</div>';
}
if (!empty($player6)) {
if (!empty($player6card)) {
echo '<div class="blackcardplaceholderplaced">';
}else{
echo '<div class="blackcardplaceholder">';
}
echo 'P6';
echo '</div>';
}
if (!empty($player7)) {
if (!empty($player7card)) {
echo '<div class="blackcardplaceholderplaced">';
}else{
echo '<div class="blackcardplaceholder">';
}
echo 'P7';
echo '</div>';
}
if (!empty($player8)) {
if (!empty($player8card)) {
echo '<div class="blackcardplaceholderplaced">';
}else{
echo '<div class="blackcardplaceholder">';
}
echo 'P8';
echo '</div>';
}
echo '</div>';
if ($headmaster == $username) {
//You are the headmaster, show the judge view
echo '<br />Your turn to <div id="headmaster">Judge</div><br /><br />';
if(!empty($thisroundwhitecard)) {
echo '<div class="bigwhitecard">';
echo $thisroundwhitecard;
echo '</div>';
}
}else{
//You are not the headmaster, show the player view
//Randomly generate 5 cards
require '../dbauth/cards.inc.php';
$cardsdbhandle = mysql_connect(
$cardshostname,
$cardsusername,
$cardspassword
) or die("INVALID USERNAME OR PASSWORD");
$cardsselected = mysql_select_db($cardsdbname, $cardsdbhandle);
$newblackcardsql = "SELECT * FROM black LIMIT 5";
$newblackcardquery = mysql_query($newblackcardsql, $cardsdbhandle);
$newblackcardcount = mysql_num_rows($newblackcardquery);
$c = 0;
if ($newblackcardcount > 0) {
echo '<div class="blackcardscroller">';
echo '<div class="blackcardscrollerinner">';
while ($c < $newblackcardcount) {
$blackcardid = mysql_result($newblackcardquery, $c, "id");
$blackcardtext = mysql_result($newblackcardquery, $c, "text");
echo '<div class="gameblackcard">';
echo $blackcardtext;
echo '<div class="blackcardbtn" id="';
echo $blackcardid;
echo '">PICK CARD</div>';
echo '</div>';
$c++;
}
echo '</div>';
echo '</div>';
}else{
//There are no black cards
echo 'There are no black cards to pick from! Something went wrong...';
}
echo '<br />Judge: <br />';
echo '<div id="headmaster">';
echo $headmaster;
echo '</div>';
if(!empty($thisroundwhitecard)) {
echo '<div class="bigwhitecard">';
echo $thisroundwhitecard;
echo '</div>';
}
}
}
?>

You should not use setInterval... Do this instead:
function refresh_div() {
jQuery.ajax({
url:'progress.php?game=<?php echo $gamename; ?>',
type:'POST',
success:function(results) {
jQuery(".middle").html(results);
setTimeout(function(){
refresh_div();
}, 1000);
}
});
}
refresh_div();

I think you problem in this string
t = setInterval(refresh_div,1000);
You get queries from servers each second, so after 10 seconds there are 10 query in row and this can cause timeouts because server too busy to answer and also it may be some other problems because to much concurrent queries. So i suggest you try use promise(), take look in this post:
in JavaScript, how to wrap a promise in timeout?

Related

Javascript code stops working after page Load More .load()

When data is fetched on auto Load More, another JavaScript (which is given below) stops working.
Even when it shows the 1st page default it works there but after scrolling down it does not work.
Updated with more explaination with index and getdata file. I'm fetching data like mentioned in the below codes.
index.php
<div>
<?php include('getdata.php'); ?>
</div>
<script>
$(document).ready(function(){
var is_ajaxed = false;
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: {rowcount:$("#rowcount").val()+1},
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){
$("#faq-result").append(data);
},
error: function(){}
});
}
$(window).scroll(function(){
if ($(window).scrollTop() >= ($(document).height() - $(window).height()-900) && is_ajaxed == false){
if($(".pagenum").val() <= $(".total-page").val()) {
var pagenum = parseInt($(".pagenum").val()) + 1;
var pname = "<?php echo $pgianame; ?>";
var sname = "<?php echo $stianame; ?>";
getresult('sellers_forum_page_posts_getresult.php?page='+pagenum+'&pname='+pname+'&sname='+sname);
is_ajaxed = true
}
}
});
});
</script>
getdata.php
<?php
include ('db.php');
$perPage = 10;
$sql = "select * from posts where status = 1";
$faq3x = $dba3->query($sql);
$allrowscount = mysqli_num_rows($faq3x);
$pages = ceil($allrowscount/$perPage);
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
}
$start = ($page-1)*$perPage;
if($start <= 0) $start = 0;
$sqlsC = "select * from posts where status = 1 ";
$query = $sql . " limit " . $start . "," . $perPage;
$faq3xsC = $dba3->query($query);
echo '<input type="text" class="pagenum" value="'.$page.'" />';
echo '<input type="text" class="total-page" value="'.$pages.'" />';
while ($faqC = $faq3xsC->fetch_assoc()) {
$id = $faqC['id'];
$ext = ".doc";
$name = $id.$ext;
$filepath = "blog/posts/";
$filename = $filepath.$name;
if(file_exists($filename)) {
if(($fhP = fopen($filename, 'r')) !== false ) {
$headersxP = fread($fhP, 999000);
$commentsPP = nl2br($headersxP);
$countxP = 0;
$fhxP = fopen($filename, 'r');
while(!feof($fhxP)){
$frxP = fread($fhxP, 999999);
$countxP += strlen($frxP);
}
fclose($fhxP);
?>
<?php echo substr($commentsPP, 0, 511); ?>
<span id="dots_<?php echo $idPost; ?>">...</span>
<span id="more_<?php echo $idPost; ?>" style="">
<?php echo substr($commentsPP, 512, 999999); ?>
</span>
<a onclick="myFunctionx_<?php echo $id; ?>()"
id="myBtn_<?php echo $id; ?>"> See More <i class="fa fa-long-arrow-right"></i></a>
<script>
function myFunctionx_<?php echo $id; ?>() {
var dots_<?php echo $id; ?> = document.getElementById("dots_<?php echo $id; ?>");
var moreText_<?php echo $id; ?> = document.getElementById("more_<?php echo $id; ?>");
var btnText_<?php echo $id; ?> = document.getElementById("myBtn_<?php echo $id; ?>");
if (dots_<?php echo $id; ?>.style.display === "none") {
dots_<?php echo $id; ?>.style.display = "inline";
btnText_<?php echo $id; ?>.innerHTML = " See more <i class='fa fa-long-arrow-right'></i>";
moreText_<?php echo $id; ?>.style.display = "none";
} else {
dots_<?php echo $id; ?>.style.display = "none";
btnText_<?php echo $id; ?>.innerHTML = " <i class='fa fa-long-arrow-left'></i> See less";
moreText_<?php echo $id; ?>.style.display = "inline";
}
}
</script>
<?php } ?>

What should I put in my updating.php when I need to update users status if online or offline every 5 seconds?

Hi I've made a messaging feature,it displays the receivers of the message in an account, beside the receiver's name is a green or red dot, for online or offline, it is successful when I log in 2 accounts and messaged each other, when I open the first account, the other account is offline, when I open the second account, the other is online, what my problem is I want to update their status in every five seconds so that their dot will be accurate whenever they log out or log in. I have made a javascript and ajax below this page left-col.php and I've tried copying the whole code, putting it to updating.php but it did not work, what should be the appropriate data inorder to update user receiver status in every 5 seconds inside the updating.php? and also, does my the javascript and ajax needs a library to be included that's why it didn't work? Please help.
<?php
require('connection.php');
$user_name=$_SESSION['username'];
$user_id=$_SESSION['user_id'];
if(!isset($_SESSION['user_id'])){
header("LOCATION: index.php");
}else{
$advance_time=time()+15;
$query=mysqli_query($con,"SELECT * FROM status WHERE user_id='$user_id'");
if(mysqli_num_rows($query)>0){
mysqli_query($con,"UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
}else{
mysqli_query($con,"INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
}
?>
<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById('new-message').style.display='block'" class="white-back">
<p align="center">New Message </p>
</div>
<?php
$q='SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="'.$_SESSION['username'].'" OR
`receiver_name`="'.$_SESSION['username'].'"
ORDER BY `date_time` DESC';
$e='SELECT * from messages';
$r=mysqli_query($con,$q);
if($r){
if(mysqli_num_rows($r)>0){
$counter=0;
$added_user=array();
while($row=mysqli_fetch_assoc($r)){
$sender_name=$row['sender_name'];
$receiver_name=$row['receiver_name'];
$timestamp=$row['date_time'];
if($_SESSION['username']==$sender_name){
//add the receiver_name but only once
//so to do that check the user in array
if(in_array($receiver_name,$added_user)){
//dont add receiver_name because
//he is already added
}else{
//add the receiver_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php
echo ''.$receiver_name.'';
$fetch_content=mysqli_query($con,"SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while($row_fetch=mysqli_fetch_array($fetch_content)){
$time=$row_fetch[5];
if($time<= time()){
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
}else{
$status= "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as receiver_name added so
///add it to the array as well
$added_user=array($counter=>$receiver_name);
//increment the counter
$counter++;
}
}elseif($_SESSION['username']==$receiver_name){
//add the sender_name but only once
//so to do that check the user in array
if(in_array($sender_name,$added_user)){
//dont add sender_name because
//he is already added
}else{
//add the sender_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php echo ''.$sender_name.'';
$fetch_content=mysqli_query($con,"SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while($row_fetch=mysqli_fetch_array($fetch_content)){
$time=$row_fetch[5];
if($time<= time()){
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
}else{
$status= "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as sender_name added so
///add it to the array as well
$added_user=array($counter=>$sender_name);
//increment the counter
$counter++;
}
}
}
}
else{
//no message sent
echo 'no user';
}
}else{
//query problem
echo $q;
}
?>
<!-- end of left-col-container -->
</div>
<input type="hidden" value="<?php echo $user_id; ?>" id="from_user_id">
<script type="text/javascript">
setInterval(function(){updating_status()},5000);
function updating_status(){
let this_user = $('#from_user_id').val();
$.ajax({
method: "POST",
url: "updating.php",
data: {from_user:this_user},
success: function(response){
$('#content').html(response);
}
});
}
</script>
You need to handle the $_SESSION in all pages
Updating.php code:
<?php
require('connection.php');
session_start();
$user_name = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
if(isset($_REQUEST['from_user'])){
$advance_time=time()+15;
$user_id = $_REQUEST['from_user'];
$query=mysqli_query($con,"SELECT * FROM status WHERE user_id='$user_id'");
if(mysqli_num_rows($query)>0){
mysqli_query($con,"UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
}
}else{
mysqli_query($con,"INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
$html_left_div = '';
$html_left_div .='<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById(\'new-message\').style.display=\'block\'" class="white-back">
<p align="center">New Message </p>
</div>';
$q = 'SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="' . $_SESSION['username'] . '" OR
`receiver_name`="' . $_SESSION['username'] . '"
ORDER BY `date_time` DESC';
$e = 'SELECT * from messages';
$r = mysqli_query($con, $q);
// echo $q;
if ($r) {
if (mysqli_num_rows($r) > 0) {
$counter = 0;
$added_user = array();
while ($row = mysqli_fetch_assoc($r)) {
$sender_name = $row['sender_name'];
$receiver_name = $row['receiver_name'];
$timestamp = $row['date_time'];
if ($_SESSION['username'] == $sender_name) {
//add the receiver_name but only once
//so to do that check the user in array
if (in_array($receiver_name, $added_user)) {
//dont add receiver_name because
//he is already added
} else {
//add the receiver_name
$html_left_div .='<div class="grey-back first">
<img src="s.jpg" class="image"/>
' . $receiver_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id` WHERE user_name = '$receiver_name'");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status ='<img src=\'r.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
} else {
$status ='<img src=\'a.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
}
}
$html_left_div .= $status.'</div>';
//as receiver_name added so
///add it to the array as well
$added_user = array($counter => $receiver_name);
//increment the counter
$counter++;
}
} elseif ($_SESSION['username'] == $receiver_name) {
//add the sender_name but only once
//so to do that check the user in array
if (in_array($sender_name, $added_user)) {
//dont add sender_name because
//he is already added
} else {
//add the sender_name
$html_left_div .='<div class="grey-back second">
<img src="s.jpg" class="image"/>
' . $sender_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id` WHERE user_name = '$sender_name'");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status ='<img src=\'r.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
} else {
$status ='<img src=\'a.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
}
}
$html_left_div .= $status.'</div>';
//as sender_name added so
///add it to the array as well
$added_user = array($counter => $sender_name);
//increment the counter
$counter++;
}
}
}
} else {
//no message sent
echo 'no user';
}
} else {
//query problem
echo $q;
}
$html_left_div .='</div>';
echo $html_left_div;
Left-col.php code:
<?php
require 'connection.php';
session_start();
$user_name = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
if (!isset($_SESSION['user_id'])) {
header("LOCATION: index.php");
} else {
$advance_time = time() + 15;
$query = mysqli_query($con, "SELECT * FROM status WHERE user_id='$user_id'");
if (mysqli_num_rows($query) > 0) {
mysqli_query($con, "UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
} else {
mysqli_query($con, "INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
}
?>
<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById('new-message').style.display='block'" class="white-back">
<p align="center">New Message </p>
</div>
<?php
$q = 'SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="' . $_SESSION['username'] . '" OR
`receiver_name`="' . $_SESSION['username'] . '"
ORDER BY `date_time` DESC';
$e = 'SELECT * from messages';
$r = mysqli_query($con, $q);
if ($r) {
if (mysqli_num_rows($r) > 0) {
$counter = 0;
$added_user = array();
while ($row = mysqli_fetch_assoc($r)) {
$sender_name = $row['sender_name'];
$receiver_name = $row['receiver_name'];
$timestamp = $row['date_time'];
if ($_SESSION['username'] == $sender_name) {
//add the receiver_name but only once
//so to do that check the user in array
if (in_array($receiver_name, $added_user)) {
//dont add receiver_name because
//he is already added
} else {
//add the receiver_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php
echo '' . $receiver_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
} else {
$status = "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as receiver_name added so
///add it to the array as well
$added_user = array($counter => $receiver_name);
//increment the counter
$counter++;
}
} elseif ($_SESSION['username'] == $receiver_name) {
//add the sender_name but only once
//so to do that check the user in array
if (in_array($sender_name, $added_user)) {
//dont add sender_name because
//he is already added
} else {
//add the sender_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php echo '' . $sender_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
} else {
$status = "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as sender_name added so
///add it to the array as well
$added_user = array($counter => $sender_name);
//increment the counter
$counter++;
}
}
}
} else {
//no message sent
echo 'no user';
}
} else {
//query problem
echo $q;
}
?>
<!-- end of left-col-container -->
</div>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<input type="hidden" value="<?php echo $user_id; ?>" id="from_user_id">
<script type="text/javascript">
setInterval(function(){updating_status()},5000);
function updating_status(){
let this_user = $('#from_user_id').val();
$.ajax({
method: "POST",
url: "updating.php",
data: {from_user:this_user},
success: function(response){
$('#left-col-container').html(response);
}
});
}
</script>

JavaScript/AJAX prints weirdly

My JavaScript/AJAX prints comments. It's all good, until I want to insert/get more than one comment. It duplicates itself. This feels like a nesting/missed parenthesis problem in my code, but I can't be able to find it...
My JS code:
$(document).ready(function(){
var url = 'comment-get.inc.php';
$.getJSON(url, function(data) {
$.each(data, function(index, item) {
var t = '';
t += '<div class="comment_holder" id="_'+item.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+item.username+'<br>';
t += ''+item.date+'<br>';
t += '<button class="button2" type="button" id="'+item.id+'">Delete</button>';
t += '</div></div>';
t += ''+item.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
});
});
add_delete_handlers();
$('#postButton').click(function(){
comment_post_btn_click();
});
function comment_post_btn_click()
{
//text in textarea with username, page and date
var _username = $('#postUsername').val();
var _page = $('#postPage').val();
var _date = $('#postDate').val();
var _message = $('#postMessage').val();
if(_message.length > 0)
{
//proceed with ajax callback
$('#postMessage').css('border', '1px solid #ABABAB');
$.post("comment-set.inc.php",
{
task : "comment-set",
username : _username,
page : _page,
date : _date,
message : _message
}
).success(
function(data)
{
//Task: Insert html into the div
comment_set(jQuery.parseJSON(data));
console.log("ResponseText: " + data);
});
}
else
{
//text in area is empty
$('#postMessage').css('border', '1px solid #FF0000');
console.log("Comment is empty");
}
//remove text after posting
$('#postMessage').val("");
}
function add_delete_handlers()
{
$('.button2').each(function()
{
var btn = this;
$(btn).click(function()
{
comment_delete(btn.id);
});
});
}
function comment_delete(_id)
{
$.post("comment-del.inc.php",
{
task : "comment-del",
id : _id
}
).success(
function(data)
{
$('#_' + _id).detach();
});
}
function comment_set(data)
{
var t = '';
t += '<div class="comment_holder" id="_'+data.comment.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+data.comment.username+'<br>';
t += ''+data.comment.date+'<br>';
t += '<button class="button2" type="button" id="'+data.comment.id+'">Delete</button>';
t += '</div></div>';
t += ''+data.comment.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
}
});
Comments.php:
<?php
class Comments {
public function set($message, $username, $date, $page) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "INSERT INTO comments VALUES ('', '$username', '$page', '$date', '$message')";
$query = mysqli_query($connect, $sql);
if($query){
$std = new stdClass();
$std->id = mysqli_insert_id($connect);
$std->message = $message;
$std->username = $username;
$std->date = $date;
$std->page = $page;
return $std;
}
return null;
}
public function del($id) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "DELETE FROM comments WHERE id = $id";
$query = mysqli_query($connect, $sql);
if($query)
{
return true;
}
}
}
?>
Comment-get.inc.php:
<?php
$page = htmlentities("/index.php?page=maplepancakes", ENT_QUOTES);
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "SELECT * FROM comments WHERE page='$page' ORDER BY id DESC";
$result = $connect->query($sql);
$data = array();
while ($row = $result->fetch_assoc()) {
$row_data = array(
'id' => $row['id'],
'username' => $row['username'],
'date' => $row['date'],
'message' => $row['message']
);
array_push($data, $row_data);
}
?>
<?php
echo json_encode($data);
?>
Comment-set.inc.php:
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-set'){
$username = $_POST['username'];
$date = $_POST['date'];
$page = $_POST['page'];
$message = $_POST['message'];
require_once 'comments.php';
if(class_exists('Comments')){
$userInfo = $username;
$commentInfo = Comments::set($message, $username, $date, $page);
$std = new stdClass();
$std->user = $userInfo;
$std->comment = $commentInfo;
echo json_encode($std);
}
}
?>
Picture of the problem (json_encode in the bottom of the picture containing 3 comments):
your comments div container has class .comment_holder so each time with new comment you prepend to all class's so create comment container with unique id an prepend to this. like this $('#comment_container').prepend(t); this with work.

PHP/HTML button picture change and script call

I have a page with buttons that a user clicks on.
When the button gets clicked I need it to change the image and call a php script to save the change.
I somehow can't get the button to do both, it changes the pic but won't call the php.
CODE:
<?php
$db = new PDO('mysql:host=localhost;dbname=MySettings;charset=utf8mb4', 'TestUser', '1234567890');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
try {
$mytable = $_SESSION["SESS_myuserid"];
if($mytable == null)
{$url='login.php';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';}
$stmt = $db->prepare("SELECT * FROM ".$mytable);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$conn = null;
echo'<script>';
$count = count($result);
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
echo 'var newsrc'.$TheId.' = "on.jpg";';
}
else{
echo 'var newsrc'.$TheId.' = "off.jpg";';
}
echo 'function changeImage'.$TheId.'() {';
echo 'if ( newsrc'.$TheId.' == "off.jpg" ) {';
echo "document.getElementById('pic".$TheId."').src = '/images/Boff.png';";
echo "$('#newCode').load('Monitor.php?id=".$TheId."&Table=".$mytable."');";
echo 'newsrc'.$TheId.' = "on.jpg";';
echo '}';
echo 'else {';
echo "document.getElementById('pic".$TheId."').src = '/images/Bon.png';";
echo "$('#newCode').load('Monitor.php?id=".$TheId."&Table=".$mytable."');";
echo 'newsrc'.$TheId.' = "off.jpg";';
echo '}';
echo '}';
}
echo'</script>';
$myLeft=0;
$myTop=0;
$myRow=0;
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
$ThePic = "images/Boff.png";
}
else{
$ThePic = "images/Bon.png";
}
echo '<div>';
echo ' ';
echo '</div>';
$myTop=$myTop + 30;
$myRow=$myRow + 1;
if ($myRow == 12){
$myRow=0;
$myTop=0;
if ($myLeft == 0){
$myLeft = 292;
}
else {
$myLeft = 615;
}
}
}
}
catch(PDOException $e) {
$url='login.php';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
}
?>
Fixed :
Changed the script function. Added a hidden div to be called to load the php which outputs nothing so stays invisible.
echo'<script>';
$count = count($result);
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
echo 'var newsrc'.$TheId.' = "on.jpg";';
}
else{
echo 'var newsrc'.$TheId.' = "off.jpg";';
}
echo 'function changeImage'.$TheId.'() {';
echo 'if ( newsrc'.$TheId.' == "off.jpg" ) {';
echo "document.getElementById('pic".$TheId."').src = '/images/Boff.png';";
echo 'newsrc'.$TheId.' = "on.jpg";';
echo '}';
echo 'else {';
echo "document.getElementById('pic".$TheId."').src = '/images/Bon.png';";
echo 'newsrc'.$TheId.' = "off.jpg";';
echo '}';
echo' $("#HtmlConvo").load("Monitor.php?id='.$TheId.'&Table='.$mytable.'");';
echo '}';
}
echo'</script>';

javascript array returns [object Window] instead of array content

I have a problem. I wrote some PHP code that echoes "var pixelArray = [];". after that it echoes a few variables like this: "var canvas$id = 'can' + $id;". and also echoes "pixelArray.push(canvas$id);" for each variable.
Now for some reason when i run the script, the array doesn't contain anything.
Can anyone explain to me why?
If you need more information, please tell me.
EDIT:
Here's my full (but still simplyfied) code:
<?php
$blockCounter = 1;
$scriptCounter = 1;
$arrayCounter = 1;
$size = 32 * 32;
$yLine = 1;
while ($blockCounter <= $size)
{
if ($blockCounter == 32 * $yLine){
echo "<canvas id=\"can$blockCounter\" width=\"17\" height=\"17\" style='border:1px solid #777777;'>GET A NEW BROWSER</canvas>";
echo "<br>";
$blockCounter = $blockCounter + 1;
$yLine = $yLine + 1;
}
else{
echo "<canvas id=\"can$blockCounter\" width=\"17\" height=\"17\" style='border:1px solid #777777;'>GET A NEW BROWSER</canvas>";
$blockCounter = $blockCounter + 1;
}
}
echo "<script>";
echo "var pixelArray = [];";
while ($arrayCounter <= $size)
{
echo "var name$arrayCounter = 'can' + $arrayCounter;";
echo "pixelArray.push(name$arrayCounter);";
$arrayCounter = $arrayCounter + 1;
}
while ($scriptCounter <= $size)
{
echo "var c = document.getElementById(\"can$scriptCounter\");";
echo "picoco$scriptCounter = c.style.backgroundColor = \"#000000\";";
$scriptCounter = $scriptCounter + 1;
}
echo "document.getElementById(\"arrayLoc\").innerHTML = pixelArray[0];";
echo "</script>";
?>
<p id="arrayLoc"></p>
document.getElementById("arrayLoc") is returning null, not the pixelArray[0]. The problem is that the paragraph tag has not been loaded into the DOM at the time of the javascript load. You can put it above the script shown below.
echo '<p id="arrayLoc"></p>';
echo "<script>"
echo "var pixelArray = [];";
while ($arrayCounter <= $size)
{
echo "var name$arrayCounter = 'can' + $arrayCounter;";
echo "pixelArray.push(name$arrayCounter);";
$arrayCounter = $arrayCounter + 1;
}
while ($scriptCounter <= $size)
{
echo "var c = document.getElementById(\"can$scriptCounter\");";
echo "picoco$scriptCounter = c.style.backgroundColor = \"#000000\";";
$scriptCounter = $scriptCounter + 1;
}
echo "document.getElementById(\"arrayLoc\").innerHTML = pixelArray[0];";
echo "</script>";
?>
Or run the javascript after the DOM has loaded.
echo "<script>";
echo "window.onload = function () {";
echo "var pixelArray = [];";
while ($arrayCounter <= $size)
{
echo "var name$arrayCounter = 'can' + $arrayCounter;";
echo "pixelArray.push(name$arrayCounter);";
$arrayCounter = $arrayCounter + 1;
}
while ($scriptCounter <= $size)
{
echo "var c = document.getElementById(\"can$scriptCounter\");";
echo "picoco$scriptCounter = c.style.backgroundColor = \"#000000\";";
$scriptCounter = $scriptCounter + 1;
}
echo "document.getElementById(\"arrayLoc\").innerHTML = pixelArray[0];";
echo "}";
echo "</script>";
?>
<p id="arrayLoc"></p>

Categories