php and ajax JavaScript pagination comment system - javascript

Trying to build a commenting system. Were comments are posted with AJAX. With comment count with Pagination. I have success achieving both, but putting them together is another story. I have tried doing 2 ajax calls. One for getting records from the database and showing pagination. The other call for recording records to the database.
// this is the first ajax call to to get the results and show pagination buttons
<script>
function request_page(pn){
var two = <?php echo $img_id; ?>;
var showmax = <?php echo SHOWMAX; ?>; // results per page
var totalpages = <?php echo $totalpages; ?>;
//controls for pigmintation
var pagination_controls = document.getElementById("pagination_controls");
var results_box = document.getElementsByClassName(two)[0];
params = 'showmax=' + showmax + '&totalpages=' + totalpages + '&pn=' + pn + '&img_id=' + two;
request = new ajaxRequest()
request.open("POST", "response5.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
results_box.innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(params)
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
var paginationCtrls = "";
// Only if there is more than 1 page worth of results give the user pagination controls
if(totalpages != 1)
{
if( pn > 1){
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+totalpages+'</b> ';
if (pn != totalpages) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
</script>
<script> request_page(<?php echo $totalpages; ?>); </script>
/// the response
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$curPage = (int) sanitizeString($_POST['pn']);
$showmax = (int) sanitizeString($_POST['showmax']);
$totalpages = (int) sanitizeString($_POST['totalpages']);
$z = (int) sanitizeString($_POST['img_id']);
if ($curPage < 1) {
$curPage = 1;
} else if ($curPage > $totalpages) {
$curPage = $totalpages;
}
$offset = ($curPage-1) * $showmax;
// var_dump($showmax);
$one = $showmax;
$getcomments = "SELECT I.comment, I.created, U.user_pic_path, U.user_id, U.username, G.file_name
FROM users U
INNER JOIN img_comment I
ON I.img_id = ?
LEFT OUTER JOIN gallery G
ON G.img_id = U.user_pic_path
WHERE I.user_id = U.user_id
ORDER BY UNIX_TIMESTAMP(created) ASC
LIMIT ?, ?";
$stmt = $pdo->prepare($getcomments);
$stmt->bindParam(1, $z, PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);
$stmt->bindParam(3, $one, PDO::PARAM_INT);
$stmt->execute();
//fetch resuls
while ($row = $stmt->fetch()){
echo "<div class='chat-entry users person triggerProfile'>";
$bulls = get_web_path($row['user_pic_path']);
if(isset($row['file_name']))
{
$done32 = "http://localhost/new11/users/{$row['username']}/thumbs/{$row['file_name']}";
}else
{
$done32 = 'http://localhostnew11/users/noimage.jpg';
}
$bulls = get_web_path($row['file_name']);
echo "<a class='head users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>
<img class='imgcom' src='$done32'>
</a>
<div class='body'>
<div class='basic'>
<span class='username'>
<a class='users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>{$row['username']} </a>
</span>
</div>
<div class='message'>{$row['comment']}
</div>
</div>
</div>";
}
}
////ajax call # 2 is triggered when ever the comment form is submitted
<div>
<form method='post' id="form<?php echo $img_id; ?>" name="<?php echo $img_id; ?>">
<textarea class='lake' name='one' placeholder="Comment" id='<?php echo $img_id; ?>'></textarea>
<input id="submit" onclick="showUser(document.getElementById(<?php echo $img_id; ?>).value, <?php echo $img_id; ?>);" type="button" value="Submit">
</form>
</div>
//// the ajax call function
function showUser(a, b){
name = a;
two = b;
yes = "form" + two;
params = 'name1=' + name + '&two1=' + two;
request = new ajaxRequest()
request.open("POST", "response10.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
document.getElementsByClassName(two)[0].innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(params)
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
document.getElementById(yes).reset();
return false;
}
The response
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
define('SHOWMAX', 5);
$q = sanitizeString($_POST['name1']);
$z = sanitizeString($_POST['two1']);
$b = sanitizeString($_SESSION['user_id']);
$sql = 'INSERT INTO img_comment (img_id, comment, user_id)
VALUES(:img_id, :comment, :user_id)';
// prepare the statement
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':img_id', $z, PDO::PARAM_INT);
$stmt->bindParam(':comment', $q, PDO::PARAM_STR);
$stmt->bindParam(':user_id', $b, PDO::PARAM_INT);
$stmt->execute();
$OK = $stmt->rowCount();
$getCount = 'SELECT COUNT(*) FROM img_comment WHERE img_id ='. $z;
// submit query and store result as $totalPix
$total = $pdo->query($getCount);
$totalCount = $total->fetchColumn();
// var_dump($totalCount);
$total = (int)$totalCount;
$totalpages = (int) ceil($total/ SHOWMAX);
$offset = ($totalpages-1) * SHOWMAX;
$one = SHOWMAX;
if($totalCount > 0){
$getcomments = "SELECT I.comment, I.created, U.user_pic_path, U.user_id, U.username, G.file_name
FROM users U
INNER JOIN img_comment I
ON I.img_id = ?
LEFT OUTER JOIN gallery G
ON G.img_id = U.user_pic_path
WHERE I.user_id = U.user_id
ORDER BY UNIX_TIMESTAMP(created) ASC
LIMIT ?, ?";
$stmt = $pdo->prepare($getcomments);
$stmt->bindParam(1, $z, PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);
$stmt->bindParam(3, $one, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch()){
echo "<div class='chat-entry users person triggerProfile'>";
$bulls = get_web_path($row['user_pic_path']);
if(isset($row['file_name']))
{
$done32 = "http://localhost/new11/users/{$row['username']}/thumbs/{$row['file_name']}";
}else
{
$done32 = 'http://localhostnew11/users/noimage.jpg';
}
$bulls = get_web_path($row['file_name']);
echo "<a class='head users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>
<img class='imgcom' src='$done32'>
</a>
<div class='body'>
<div class='basic'>
<span class='username'>
<a class='users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>{$row['username']} </a>
</span>
</div>
<div class='message'>{$row['comment']}
</div>
</div>
</div>";
}
}
}

Related

Getting Undefined index when making a session

Hi I'm trying to make a session in my main page but its just giving me an error of undefined index in uniqueID line 5.
The connection between my webqr.js and server.php have no errors but when I tried to connect it to my wow.php it gives me an error of undefined index.
webqr.js Code
function read(a){
var html=htmlEntities(a);
var audio = new Audio('lib/beep.ogg');
audio.play();
var uniqueID = document.getElementById("mapo").innerHTML= html;
window.location.href = "http://localhost/QR_JEFF/server.php?uniqueID=" + uniqueID; }
server.php Code
session_start();
$db = mysqli_connect('localhost', 'root','','suffrage');
$uniqueID = $_GET['uniqueID'];
$query = "SELECT * FROM applicant_table WHERE unique_id='$uniqueID'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$logged_in_user = mysqli_fetch_assoc($results);
if($logged_in_user['validation_status'] == 'Verified' && $logged_in_user['voting_status'] == 'No'){
$_SESSION['unique_id'] = $uniqueID;
$_SESSION['validation_status'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: wow.php');
}
}
wow.php Code
<?php include('server.php');?>
<?php if (isset($_SESSION['unique_id'])) : ?>
Welcome User:
<input type="text" value="<?php echo $_SESSION['unique_id']; ?>" disabled>
<?php endif ?>
Now I'm receiving this error.
okay so this solve my own question.
session_start();
if(isset($_GET['uniqueID'])){
$uniqueID = " ";
$db = mysqli_connect('localhost', 'root','','suffrage');
$uniqueID = $_GET['uniqueID'];
$query = "SELECT * FROM applicant_table WHERE unique_id='$uniqueID'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$logged_in_user = mysqli_fetch_assoc($results);
if($logged_in_user['validation_status'] == 'Verified' && $logged_in_user['voting_status'] == 'No'){
$_SESSION['unique_id'] = $uniqueID;
$_SESSION['validation_status'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: wow.php');
}
}
}
I put my code in another if statement.

Why is this AJAX call not working in IE 11?

I have a notifications system on my site, that utilizes AJAX to update in real-time. The problem is that it works on every browser except IE 11. After looking around I noticed some people advising to use cache:false in the call. However, this makes the code non-functional across all browsers. Anyone know what the solution is?
JAVASCRIPT:
<script>
$(document).ready(function(){
$('.notif_count').html('0');
function load_unseen_notification(view = '')
{
$.ajax({
url:"notif_follow.php",
method:"POST",
data:{view:view},
dataType:"json",
success:function(data)
{
$('.notif_follow').html(data.notification);
if(data.notif_count > 0)
{
$('.notif_count').html(data.notif_count);
}
}
});
}
load_unseen_notification();
$(document).on('click', '.notif', function(){
$('.notif_count').html('0');
load_unseen_notification('yes');
});
setInterval(function(){
load_unseen_notification();;
}, 5000);
});
</script>
PHP:
<?php
session_start();
require_once 'class.channel.php';
$user_notif = new USER();
$user_id = $_SESSION['userID'];
if(isset($_POST["view"]))
{
if($_POST["view"] != '')
{
$stmt = $user_notif->runQuery("UPDATE notif_follow SET status = 1 WHERE receive_id = ?");
$stmt->bindValue(1,$user_id);
$stmt->execute();
}
$stmt = $user_notif->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? ORDER BY id DESC LIMIT 5");
$stmt->bindValue(1,$user_id);
$stmt->execute();
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$notification = '';
if(count($notifs) > 0)
{
foreach($notifs as $notif)
{
$send_id = $notif['send_id'];
$query2 = $user_notif->runQuery("SELECT * FROM following WHERE user1_id=:uid1 AND user2_id=:uid2");
$query2->execute(array(":uid1"=>$user_id,":uid2"=>$send_id));
$query2result = $query2->fetchAll(PDO::FETCH_ASSOC);
if(count($query2result) > 0){
$follow = '<button class="button" style="margin:2px;">Remove Channel</button>';
}
else{
$follow = '<button class="button" style="margin:2px;">Add Channel</button>';
}
$notification .= '
<li>
<div class="notifbox">
<strong style="color: #4b8ed3;">'.$notif["send_name"].'</strong><p style="color: #fff;"> has added you.</p>
'.$follow.'
<button class="button" style="margin:2px;">View Channel</button>
</div>
</li>
<div class="sectionheader3"></div>
';
}
}
else
{
$notification .= '<li><h2 style="color: #4b8ed3; padding: 10px;">No Notifications Found<h2></li>';
}
$count = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? AND status= 0");
$count->bindValue(1,$user_id);
$count->execute();
$countresult = $count->fetchAll(PDO::FETCH_NUM);
if(count($countresult) > 0){
$notif_count = count($countresult);
}
else{
$notif_count = 0;
}
header('Content-type: application/json');
$notif_array = array('notification'=>$notification,'notif_count'=>$notif_count);
echo json_encode($notif_array);
}
?>

how to add characters to the end of the value if it already exists?

Here when I click post button it inserts a random value on database.
If a value already exists on database then show error. It works fine.
But I want to add 2/3 characters at the end of value if it already exists on database. If $check == 1 then I want to add some characters at the end of the value instead of showing alert. How to do this?
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
// if $check==1 then i want to add 2 characters at the end of $slug .
if($check == 1)
{
// instead of showing alert i want to add 2 more characters at the end of that value and and insert it on database
echo "<script> alert('something is wrong') </script> ";
exit ();
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>
<form method="POST" >
<?php
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$chararray = str_split($chars);
for($i = 0; $i < 7 ; $i++)
{
$randitem = array_rand($chararray);
$result .= "".$chararray[$randitem];
}
echo $result ;
?>
<input type="hidden" value="<?php echo $result;?>" name="rand" />
<span class="input-group-btn">
<button class="btn btn-info" type="submit" name="submit">POST</button>
</span>
</form>
just run update query if $check == 1
if($check == 1){
$newSlug = $slug."xy";
$update = "update slug set post_slug = '".$newSlug."' where post_slug = '".$slug."'";
$run = mysqli_query($con,$update );
echo "<script> alert('Updated Successfully') </script> ";
exit ();
}
This is helpful for you
<?php
$con = mysqli_connect("localhost","root","","post" ) or die
( "unable to connect to internet");
if(isset($_POST['submit'])){
$tmp_slug = $_POST['rand'];
$slug = $_POST['rand'];
while(check_exiest($tmp_slug))
{
$tmp_rand = rand(11,99);
$tmp_slug = $slug.$tmp_rand;
}
$insert ="insert into slug (post_slug) values ('$tmp_slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
public function check_exiest($slug)
{
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check >= 1)
{
return true;
}
else
{
return false;
}
}
?>
Just few modification in your code to insert new value.
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check == 1)
{
$slug_new = $slug.'ab'; // Add 2 characters at the end
$update ="UPDATE slug SET post_slug = '$slug_new' WHERE post_slug = '$slug'";
$run = mysqli_query($con,$update);
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>

Why does php code not recognize a database update?

I have some php and html code and a small bit of JavaScript. Its a like system. Click the like button or dislike button and when you exit/leave the page the JavaScript and ajax runs a php file to update the database with the changes.(+1 to likes or +1 to dislikes or -1 to dislikes etc.) There is one problem. I click like/dislike and then i leave/ refresh page and the likes have not changed in value. If i dont click anything, which means im not updating the database and i refresh/leave a second time the likes are updated on the screen to what they should be. The database gets updated when its suppose to, its the code that dosnt use the new value for whatever reason. Here's my code:
<?php
session_start();
error_reporting(0);
$GOTID = $_GET['id'];
$GOTtitle = $_GET['title'];
include_once "mysql_connect.php";
include_once "like.php";
//include_once "dislike.php";
$email ='';
$log = null;
$log1 = null;
if(isset($_SESSION["ID"])){
$log1 = $_SESSION["ID"];
}else{
$log1=null;
}
if(isset($_SESSION["EMAIL"])){
$log = $_SESSION["EMAIL"];
$email = $_SESSION["EMAIL"];
// echo $email;
}else{
$log=null;
}
$_SESSION["EMAIL"] = $log;
$title = "";
$text="";
$tags = "";
$views = "";
$likes = "";
$dislikes = "";
$id = "";
$userid = "";
$date = "";
$thumbnail = "";
$imageext = "";
$texttype = "";
$data = mysql_query("SELECT * FROM videos WHERE id=$GOTID");
while ($row = mysql_fetch_array($data)) {
$title = $row[0];
$descrip = $row[1];
$id = $row[2];
$userid = $row[3];
$date = $row[4];
$views = $row[5];
$likes = $row[6];
$dislikes = $row[7];
$thumbnail = $row[8];
$imagext = $row[10];
$videourl = $row[11];
}
if($likes != '0' || $dislikes !='0'){
$total = $likes + $dislikes;
$likebar = round(($likes / $total) * 100);
$finlikes = (($likebar * 150)/100);
}else{
$finlikes = 150;
}
$query5 = mysql_query("UPDATE `videos` SET `views` = `views`+1 WHERE `videos`.`id` = $GOTID;");
$stop = false;
$fetchlast = mysql_query("SELECT `id` FROM videos WHERE id=(SELECT MAX(id) FROM videos)");
$lastrow = mysql_fetch_row($fetchlast);
$lastid = $lastrow[0];
for ($i=1; $i <= $lastid; $i++) {
if($GOTID == $id){
$stop = true;
break;
}else{
if($i >=$lastid && $GOTID != $id){
$stop = false;
header('HTTP/1.0 404 Not Found');
$_GET['e'] = 404;
die();
exit;
}
}
}
$username = '';
$userrep = '';
$rank = '';
$imageData = '';
$currentname = mysql_query("SELECT * FROM allaccounts WHERE id=$userid");
while ($row = mysql_fetch_array($currentname)) {
$username = $row[0];
$rank = $row[3];
$userrep = $row[7];
$data = $row["image"];
$ext = $row["filetype"];
// $img1 = Img_Resize($data);
// $imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
}
$liked = false;
$disliked = false;
$done = false;
$thing = mysql_query("SELECT `id` FROM likes WHERE id=(SELECT MAX(id) FROM likes)");
$lastrow = mysql_fetch_row($thing);
$lastid = $lastrow[0];
if($lastid == null || $lastid == '0'){
$lastid = '1';
}
$state1 = '';
for ($i=1; $i <= $lastid+1; $i++) {
$current = mysql_query("SELECT * FROM likes WHERE id=$i");
while ($row = mysql_fetch_array($current)) {
$id1 = $row[0];
$userid1 = $row[1];
$state1 = $row[2];
$articleid1 = $row[3];
if($done == false){
if($email == $userid1 && $articleid1 == $id && $state1 == '1'){
$liked = true;
$disliked = false;
$done = true;
break;
}else{
$liked = false;
}
if($email == $userid1 && $articleid1 == $id && $state1 == '0'){
$disliked = false;
$liked = false;
$done = true;
break;
}
if($email == $userid1 && $articleid1 == $id && $state1 == '2'){
$disliked = true;
$liked = false;
$done = true;
break;
}else{
$disliked = false;
}
}
}
}
$donetitle = str_replace(" ", "-", $title);
$_SESSION["prevpage"] = "video/".$id."/".$donetitle."";
$lik = mysql_query("SELECT * FROM videos WHERE id=$GOTID");
while ($row22 = mysql_fetch_array($lik)) {
$Olikes = $row22[6];
}
$dis = mysql_query("SELECT * FROM videos WHERE id=$GOTID");
while ($row22 = mysql_fetch_array($dis)) {
$Odislikes = $row22[7];
}
?>
<html>
<head>
<title><?php echo $title;?></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"language="javascript" type="text/javascript"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/javascript">
var likes = <?php echo $likes;?>;
var dislikes = <?php echo $dislikes;?>;
</script>
<div class = "container_24">
<header>
</header>
<div class = "main clearfix">
<div class ="grid_24 ">
<div id = "rectarticletop">
<a onclick='like()' id="likebtn"><img id="alike"src="img/icons/like.png" alt = "like"/></a>
<div id="dislikes"><div style="width:<?php echo($finlikes);?>;" id="likes"></div></div>
<a onclick="dislike()" id="dislikebtn"><img id="adislike" src="img/icons/dislike.png" alt = "dislike" /></a>
<p id= "likesnum"><?php echo $likes; ?></p>
<p id= "dislikesnum"><?php echo $dislikes; ?></p>
<script type="text/javascript">
var Liked = "<?php echo $liked;?>";
var Disliked = "<?php echo $disliked;?>";
var Art = "<?php echo $id;?>";
var User = "<?php echo $email;?>";
var olikes = "<?php echo $Olikes;?>";
var odislikes = "<?php echo $Odislikes;?>";
var state = "<?php echo $state1; ?>";
if(Liked == null){
Liked = false;
}
if(Disliked == null){
Disliked == false;
}
if(!Liked){
console.log("not liked!");
}
if(!Disliked){
console.log("not disliked!");
}
var loged = "<?php echo($log);?>";
window.onbeforeunload = function() {
$.ajax({
type: "GET",
url: 'dealLikes.php?article='+Art+'&user='+User+'&state=1&likes='+likes+'&dislikes='+dislikes+'&Olikes='+olikes+'&Odislikes='+odislikes+'&prev='+state+'',
success: function(data){
console.log("Its done!");
}
});
};
setInterval(function changetext(){
document.getElementById('likesnum').innerHTML = likes;
document.getElementById('dislikesnum').innerHTML = dislikes;
if(Liked){
document.getElementById('alike').src = "img/icons/like1.png";
}else{
document.getElementById('alike').src = "img/icons/like.png";
}
if(Disliked){
document.getElementById('adislike').src = "img/icons/dislike1.png";
}else{
document.getElementById('adislike').src = "img/icons/dislike.png";
}
},20);
function like(){
if(loged){
if(Liked){
likes-=1;
Liked = false;
// document.getElementById('alike').src = "img/icons/like.png";
}else if(Disliked){
dislikes-=1;
Disliked = false;
likes+=1;
Liked = true;
// document.getElementById('alike').src = "img/icons/like1.png";
// document.getElementById('adislike').src = "img/icons/dislike.png";
}else{
likes+=1;
Liked = true;
// document.getElementById('alike').src = "img/icons/like1.png";
}
}else{
window.location = "login";
}
}
function dislike(){
if(loged){
if(Disliked){
dislikes-=1;
Disliked = false;
// document.getElementById('adislike').src = "img/icons/dislike.png";
}else if(Liked){
likes-=1;
Liked = false;
dislikes+=1;
Disliked = true;
// document.getElementById('adislike').src = "img/icons/dislike1.png";
//document.getElementById('alike').src = "img/icons/like.png";
}else{
dislikes+=1;
Disliked = true;
// document.getElementById('adislike').src = "img/icons/dislike1.png";
}
}else{
window.location = "login";
}
}
</script>
</div>
</div>
</div>
</div>
</body>
</html>
What is wrong with the code that makes it not update the amount of likes on the first refresh but does update on the second refresh?

How to push data from database and see vote count after each data?

What I'm trying to do is to allow students answer questions and see each vote after each question and then the teacher can push the next question. The votes will then be entered into the database which I can use to produce a chart. I currently have the student answering questions but I'm having problem on stopping the next question from coming so the poll vote can show and how to show the vote before the next question comes.
This gets the questions from the database:
function getQuestion(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
var response = hr.responseText.split("|");
if(response[0] == "finished"){
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
hr.send();
function post_answer(){
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid="+id+"&radio="+x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if(p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
alert("Your answer was submitted"+ p.responseText);
var url = 'quiz.php?question=<?php echo $next; ?>';
window.location = url;
}
}
p.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
On a different php file:
require_once 'core/init.php';
$arrCount = "";
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$output = "";
$answers = "";
$q = "";
$connection = mysqli_connect('localhost', 'root', '', 'alsp');
$sql = mysqli_query($connection,"SELECT id FROM questions");
$numQuestions = mysqli_num_rows($sql);
if(!isset($_SESSION['answer_array']) || $_SESSION['answer_array'] < 1){
$currQuestion = "1";
}else{
$arrCount = count($_SESSION['answer_array']);
}
if($arrCount > $numQuestions){
unset($_SESSION['answer_array']);
header("location: start-quiz.php");
exit();
}
if($arrCount >= $numQuestions){
echo 'finished|<p>There are no more questions. Please enter your username and submit</p>
<form action="userAnswers.php" method="post">
<input type="hidden" name="complete" value="true">
<input type="text" name="username">
<button class="btn btn-action" type="submit" value="finish">Submit</button>
</form>';
exit();
}
$singleSQL = mysqli_query($connection,"SELECT * FROM questions WHERE id='$question' LIMIT 1");
while($row = mysqli_fetch_array($singleSQL)){
$id = $row['id'];
$thisQuestion = $row['question'];
$type = $row['type'];
$question_id = $row['question_id'];
$q = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysqli_query($connection,"SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
while($row2 = mysqli_fetch_array($sql2)){
$answer = $row2['answer'];
$correct = $row2['correct'];
$answers .= '<label style="cursor:pointer;"><input type="radio" name="rads" value="'.$correct.'">'.$answer.'</label>
<input type="hidden" id="qid" value="'.$id.'" name="qid"><br /><br />
';
}
$output = ''.$q.','.$answers.',<span id="btnSpan"><button onclick="post_answer()"class="btn btn-action">Submit</button></span>';
echo $output;
}
}
I'm guessing rather than have a submit button that takes you to the next page, after clicking on a radio button, the vote should show and then the teacher can push the next question. That's were the main issue is.

Categories