Why does php code not recognize a database update? - javascript

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?

Related

getting unexpected output from ajax

I am creating wishlist where I am sending data via ajax but it's not returning data as I implemented in the code I fail to figure out what is the main reason behind this. Here is the code
<li><span><i style="color:red;" class="<?php
if(isset($_SESSION['email'])){
$selwishlist = $con->prepare("SELECT * FROM wishlist WHERE user_id =:userid and product_id =:productid ");
$selwishlist->bindParam(":userid",$userid);
$selwishlist->bindParam(":productid",$id);
$selwishlist->execute();
$selresultwishlis = $selwishlist->rowCount();
if($selresultwishlis > 0){
echo "fa fa-heart";}else{
echo "ion-android-favorite-outline";
}}else{
echo "ion-android-favorite-outline";
}
?> wishlist-click" id="wishlist-product-id-<?php echo $id; ?>"></i></span>
</li>
if(isset($_SESSION['email'])){
$email = $_SESSION['email'];
$userdetail = $con->prepare("SELECT * FROM user WHERE email = :email");
$userdetail->bindParam(":email",$email);
$userdetail->execute();
$userres = $userdetail->fetch();
$userid = $userres['id'];
}
else{
$email = '';
$userid = '';
}
This is my input button Where first I check if the session is running or not an then check if the item is in the user wishlist or not and according to that I change the class of wishlist icon
$(".wishlist-click").click(function(e){
e.preventDefault();
var el = $(this);
alert('I am clicked')
var ids = this.id;
var splitids = ids.split('-');
var wishlistid = splitids[3];
$.ajax({
url:'wishlistajax.php',
type:'POST',
data:{ids:wishlistid},
success:function(response){
if(response == 1){
alert('1');
}else if(response == '0'){
alert('0');
}else if(response == '3'){
alert('its 3');
}
else{
alert('Not in All');
}
}
});
});
This is my jquery code and I am getting Not in both in response AND HERE IS MY AJAX CODE
<?php
session_start();
if(isset($_SESSION['email'])){
echo "1";
exit();
if(isset($_POST['ids'])){
$email = $_SESSION['email'];
$productid = htmlspecialchars($_POST['ids']);
include "conn.php";
$userdetail = $con->prepare("SELECT * FROM user WHERE email = :email");
$userdetail->bindParam(":email",$email);
$userdetail->execute();
$userres = $userdetail->fetch();
$userid = $userres['id'];
$ip = $_SERVER['REMOTE_ADDR'];
$insertquery = $con->prepare("INSERT INTO wishlist (product_id, user_id) VALUES (:productid, :userid)");
$insertquery->bindParam(":productid",$productid);
$insertquery->bindParam(":userid",$userid);
$insertquery->execute();
echo 'Item added';
exit();
}}
else{
echo '2';
header("location:loginregister.php");
exit();
}
echo '3';
exit();
?>

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);
}
?>

php and ajax JavaScript pagination comment system

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

Alert box is not showing in codeigniter models

in the model alert is not working. if condition is working,the only problem with the alert box, its not showing the dialog box.Please help..
public function setJumlahPenumpang ($idJadwal,$idPemesanan,$jml,$booked,$selected){
$data1 = $this->db->query('select p.jumlah_kursi, j.jumlah_penumpang, p.harga from tb_po p JOIN tb_jadwal j ON j.id_po = p.id_bus WHERE j.id_jadwal ='. $idJadwal);
foreach ($data1->result_array() as $dataa1) {
$tersedia = $dataa1['jumlah_kursi'] - $dataa1['jumlah_penumpang'];
if($tersedia < $jml){
?>
<script type="text/javascript">
document.location = '<?php echo base_url(); ?>proses/cekKode1/<?php echo $idPemesanan ?>';
alert("Tidak ada Bus Beroperasi");
</script>
<?php
}else{
$data3 = $dataa1['harga'] * $jml;
$this->db->query('update tb_pemesanan set harga = '.$data3.' where id_pemesanan = '.$idPemesanan);
$data = $this->db->query('select jumlah_penumpang from tb_jadwal where id_jadwal ='. $idJadwal);
$this->db->query("update tb_jadwal set booked = '".$booked."' where id_jadwal = ".$idJadwal);
$this->db->query("update tb_pemesanan set kursi = '".$selected."' where id_pemesanan = ".$idPemesanan);
foreach ($data->result_array() as $dataa) {
$data2 = $dataa['jumlah_penumpang'] + $jml;
$this->db->query('update tb_jadwal set jumlah_penumpang = '.$data2.' where id_jadwal = '.$idJadwal);
}
}
}
}
Try Echo Before Script Tag I hope So it 'll work....
if($package_id == NULL) {
echo '<script type="text/javascript">
window.location.href = "'.base_url().'"
</script>';
return;
die();
}

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