Inserting into mysql from javascript - javascript

I am attempting to build a basic higher or lower game in javascript and insert the results into a table in mysql. After that I am attempting to display the top ten results. Currently I have a rough outline of the game that functions with but am stuck on how to pass the three java script variables to php to insert. I looked up a method of doing this in Ajax an attempted to implement but have not had success yet.
<!DOCTYPE html>
<html>
<?php
session_start();
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
print $username;
}
?>
<body onload="random()">
<p>Welcome to the higher or lower game</p>
<p>Please enter a guess betweeen 1 and 100</p>
<form id="userGuess">
<input id="ui" type="text" name="UserInput" value="">
</form>
<br>
<br><br>
higher or lower
<br><br>
<p id="demo"></p>
<p id="status"></p>
<p id="rand"></p>
<p id="nan"></p>
<button onclick="comparison()">Submit</button>
<button onclick="reset()">Reset</button>
<script>
var numGuess = 0;
var userIn;
var randNum = 0;
var status;
var method;
//var nan;
function comparison(){
//isnan and parseint
userIn = document.getElementById("ui").value;
//suserIn = parseint(userIn);
//if(isnan(parseint(userIn)){
// nan = "true"
//}
//else{
// nan = "false"
//}
if(userIn == randNum){
//User wins
status = "Correct"
method = "submitScore";
getData({method:"submitScore", score:numGuess, username:username});
window.location = 'http://icarus.cs.weber.edu/~ka14804/3750/A1/results.php'
}
else if(userIn < randNum){
//output higher
status = "Higher"
numGuess++;
}
else if(userIn > randNum){
//output lower
status = "Lower"
numGuess++;
}
document.getElementById("status").innerHTML = status;
document.getElementById("demo").innerHTML = userIn;
document.getElementById("rand").innerHTML = randNum;
document.getElementById("nan").innerHTML = nan;
document.getElementById("nan").innerHTML = numGuess
;
//compare random number to user input. Output higher, lower or match.
}
function reset(){
random();
numGuess = 0;
}
function random() {
randNum = Math.floor((Math.random() * 100) + 1);
}
function getData(obj,callback){
$.ajax({
url: 'resulta.php',
type: 'GET',
dataType: "json",
data: obj
}).done(function(data) {
if(callback != null)
callback(data);
});
}
</script>
</body>
</html>
results.php
<?php
class Results {
public $data;
public $success = true;
public $errorMessage;
}
$func = $_GET["method"];
$obj = new Results();
switch ($func) {
case "getHighScores":
$conn = new mysqli('localhost','','','');
if (!$conn->connect_errno) {
$high = "SELECT * FROM HighScores ORDER BY Score LIMIT 10";
$scores = $conn->query($high);
$arr = array();
while ($row = $scores->fetch_assoc()){
$arr[] = $row;
}
$obj->data = $arr;
echo json_encode($obj);
}
break;
case "submitScore":
$userName = $_GET["username"];
$score = $_GET["score"];
$conn = new mysqli('localhost','','','');
if (!$conn->connect_errno) {
$query = "INSERT INTO HIGHSCORES VALUES('" . $userName . "', '" . $score . "')";
$conn->query($query);
}
break;
default:
echo "Invalid method";
break;
}
?>

Related

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 auto increment a number everytime when a button is clicked on other page using javascript

I have a form created using HTML and CSS, this form is not for submitting any data in fact it's only for printing purposes.
This form has an input field at top left corner to put a unique 6 digit number to uniquely identify each form.
On the homepage, there is a button link to that form page and I want to increment that serial no which is by default 000000 every time a link button to this form page is clicked.
index.html:
form-1.html:
<input class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">
You have two solution:
Using cookie
Using browser-session
Note: Please comment another solution, while using one solution
main-page.html
<html>
<head>
<title>Main Page</title>
</head>
<body>
Print
</body>
</html>
form-1.html
<html>
<head>
<title>Form Printing</title>
</head>
<body onload="loadNextSeqToForm()">
<form>
<input id="serial" class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">
</form>
</body>
<script>
/*
//Solution 1: Using Cookies
function getNextSeq() {
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);//Trim the empty space if exists
}
if (c.indexOf("next") == 0) {
var fragments = c.split("=");
if(fragments.length == 2 && !isNaN(fragments[1])) {
return parseInt(fragments[1]) + 1;
}
}
}
return "1";//default
}
function loadNextSeqToForm() {
var nextValue = getNextSeq();
document.cookie = "next=" + nextValue + ";";
document.getElementById("serial").value = formatToSixCharacters(nextValue);
}
function formatToSixCharacters(num) {
var numStr = num + "";
if(numStr.length < 6) {
var zeros = 6 - numStr.length;
for(var i = 1; i <= zeros; i++) {
numStr = "0" + numStr;
}
}
return numStr;
}
*/
//Solution 2: Using Session
function loadNextSeqToForm() {
var nextValue = sessionStorage.getItem("next") != null? sessionStorage.getItem("next") : 1;
document.getElementById("serial").value = formatToSixCharacters(nextValue);
sessionStorage.setItem("next", parseInt(nextValue) + 1)
}
function formatToSixCharacters(num) {
var numStr = num + "";
if(numStr.length < 6) {
var zeros = 6 - numStr.length;
for(var i = 1; i <= zeros; i++) {
numStr = "0" + numStr;
}
}
return numStr;
}
</script>
</html>
++ Code using PHP and MySQL
main-page.html
<html>
<head>
<title>Main Page</title>
</head>
<body>
<!-- Note this time we have to use PHP file reference -->
Print
</body>
</html>
form-1.php
<?php
session_start();
function getNextSequnceNumber() {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "orders";
$nextSeq = 1;
$conn = new mysqli($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT next_seq FROM order_sequence";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
if($row = $result->fetch_assoc()) {
$nextSeq = $row["next_seq"];
}
}
//Update next sequence number in db
$sql = "UPDATE order_sequence SET next_seq = ".($nextSeq + 1);
if (mysqli_query($conn, $sql)) {
//Updated successfully
//Write in log may be
}
$conn->close();
return formatToSixCharacters($nextSeq);
}
function formatToSixCharacters($num) {
$numStr = $num . "";
if(strlen($numStr) < 6) {
$zeros = 6 - strlen($numStr);
for($i = 1; $i <= $zeros; $i++) {
$numStr = "0" . $numStr;
}
}
return $numStr;
}
?>
<html>
<head>
<title>Form Printing</title>
</head>
<body>
<form>
<input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
</form>
</body>
</html>
DB Scripts
CREATE DATABASE orders;
USE orders;
CREATE TABLE order_sequence (
next_seq INT NOT NULL
);
-- DEFAULT VALUE
INSERT INTO order_sequence (next_seq)
VALUES(1);
Note: Make sure you replace your DB user name and password
SQLITE3 version of code as requested
form-sqlite.php
<?php
session_start();
class DBUtil extends SQLite3 {
function __construct() {
//Open db
$this->open("orders.db");
}
function createTableIfNotExists() {
//create table if not exists already
$sql = "CREATE TABLE IF NOT EXISTS order_sequence ("
." next_seq INT NOT NULL"
.")";
$result = $this->exec($sql);
return $result;//Whether table created successfully or not
}
function updateNextSeqNumber($nextSeq) {
//update next sequnce number in db
$sql = "UPDATE order_sequence SET next_seq = ".$nextSeq;
$result = $this->exec($sql);
return $result;
}
function insertFirstTime() {
//insert first time
$sql = "INSERT INTO order_sequence (next_seq) VALUES (1)";
$result = $this->exec($sql);
return $result;
}
function getNextSeq() {
//get next sequence number
$sql = "SELECT next_seq FROM order_sequence";
$result = $this->query($sql);
$nextSeq = 1;
if($row = $result->fetchArray(SQLITE3_ASSOC)) {
$nextSeq = $row["next_seq"];
} else {
$this->insertFirstTime();//First sequence number, so that next update queries will be always successfull
}
$this->updateNextSeqNumber($nextSeq + 1);
return $nextSeq;
}
}
function getNextSequnceNumber() {
//Create new object of utility class
$db = new DBUtil();
if(!$db){
die("Connection failed: " . $db->lastErrorMsg());
}
//Check if connected
if($db->createTableIfNotExists()) {
$nextSeq = $db->getNextSeq();
return formatToSixCharacters($nextSeq);
} else {
die ("Error: " . $db->lastErrorMsg());
}
//close connection finally
$db->close();
}
function formatToSixCharacters($num) {
$numStr = $num . "";
if(strlen($numStr) < 6) {
$zeros = 6 - strlen($numStr);
for($i = 1; $i <= $zeros; $i++) {
$numStr = "0" . $numStr;
}
}
return $numStr;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form Printing</title>
</head>
<body>
<form>
<input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
</form>
</body>
</html>
++PHPDesktop With Sqlite Version
form-php-desktop-sqlite.php
Please include this PHPDesktop Helper file pdo.php provided by PHPDesktop. However this is small helper file, it does not serve big purpose, but it will help you for now.
Also read Using Sqlite with PHP Desktop
<?php
session_start();
include "./pdo.php";
function getNextSequnceNumber() {
//Open connection
$db_file = "./orders.sqlite3";
PDO_Connect("sqlite:$db_file");
//Create table if not exists
$sql = "CREATE TABLE IF NOT EXISTS order_sequence ("
." next_seq INT NOT NULL"
.")";
PDO_Execute($sql);
//get next sequence number
$sql = "SELECT next_seq FROM order_sequence";
$nextSeq = PDO_FetchOne($sql);
if($nextSeq == null) {
$nextSeq = 1;
//Also insert first time record
$sql = "INSERT INTO order_sequence (next_seq) VALUES (1)";
PDO_Execute($sql);
}
//Update next time sequence
$sql = "UPDATE order_sequence SET next_seq = ".($nextSeq + 1);
PDO_Execute($sql);
return formatToSixCharacters($nextSeq);
}
function formatToSixCharacters($num) {
$numStr = $num . "";
if(strlen($numStr) < 6) {
$zeros = 6 - strlen($numStr);
for($i = 1; $i <= $zeros; $i++) {
$numStr = "0" . $numStr;
}
}
return $numStr;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form Printing</title>
</head>
<body>
<form>
<input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
</form>
</body>
</html>
A really simple way to do this is by using jQuery. Use the click event listener with the button link which will listen to every clicks made to that button, and increment the value with each clicks. With the starting value as 000000, store the incremented value into a variable and then use that variable on a desired page.
FOR EXAMPLE:
Consider that you have this button on the home.html page:
BUTTON
Now, using jQuery - listen to the click events from this link and store the incremented values on variable like this:
var count = 0,
default = '000000';
$('#linkcounter').click(function(e) {
e.preventDefault();
count++;
var ctxt = '' + count;
var incrementval = pad.substr(0, pad.length - ctxt.length) + ctxt;
});
// store the value into the local storage of DOM for the current session. this is done to retain the variable value even after a page is refreshed.
var incrementvallocal = incrementval;
localStorage.setItem("incrementvalueper", incrementvallocal);
The incremented value stored in the variable incrementval is sent to the localstorage. Now just use the value of this variable on desired page(in this example it is formpage.html).
If you want to set the placeholder text on the form page which has an input field like this:
<input class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">
by the incremented value, then use this jQuery code:
// get incremented value from the local storage of DOM.
var getincval = localStorage.getItem("incrementvalueper");
$(document).ready(function(){
$('.serial-no').attr("placeholder", getincval);
});
This code uses the value of the variable getincval(which has the incremented click value) and sets it to the placeholder text of the input element which has the class .serial-no.
Let me know if this helps. :)

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

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.

Error: JSON.parse: unexpected non-whitespace character after JSON data

I have a problem with Json pars, I have seen tons of users had this problem I saw them all but I couldn't understand where my error is in my code! Sorry if this is duplicate!
First file index.html:
This is in the head section of the file:
<script type="text/javascript">
function ajax_json_data(){
var databox = document.getElementById("databox");
var field1 = document.getElementById("field1").value;
var results = document.getElementById("results");
var x = new XMLHttpRequest();
x.open( "POST", "test.php", true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.onreadystatechange = function() {
if(x.readyState == 4 && x.status == 200){
databox.innerHTML = "";
var d = JSON.parse(x.responseText);
for(var o in d){
if(d[o].title){
results.innerHTML = "";
databox.innerHTML += '<p>'+d[o].title+'<br />';
databox.innerHTML += ''+d[o].cd+'</p>';
}
}
}
}
x.send("limit=4&field1="+field1);
results.innerHTML = "requesting...";
}
</script>
This is in the body section of the file:
<form id="form" method="post" onSubmit="return false;">
<textarea id="field1" name="field1" placeholder="Input some text here..."></textarea>
<input type="submit" id="submit" name="submit" value="Submit" onClick="ajax_json_data();">
</form>
<div id="results"></div>
<div id="databox"></div>
<script type="text/javascript">ajax_json_data();</script>
The second file test.php:
<?php header("Content-Type: application/json");
if (isset($_POST['field1']) && $_POST['field1'] != "") {
$field1 = $_POST['field1'];
require_once("db_conx.php");
$sqlString = "INSERT INTO test_ajax (title) VALUES ('$field1')";
$query = mysqli_query($db_conx, $sqlString) or die (mysqli_error());
}
if(isset($_POST['limit'])){
$limit = preg_replace('#[^0-9]#', '', $_POST['limit']);
require_once("db_conx.php");
$i = 0;
$jsonData = '{';
$sqlString = "SELECT * FROM test_ajax ORDER BY creationdate DESC LIMIT $limit";
$query = mysqli_query($db_conx, $sqlString);
while ($row = mysqli_fetch_array($query)) {
$i++;
$id = $row["id"];
$title = $row["title"];
$cd = $row["creationdate"];
$cd = strftime("%B %d, %Y", strtotime($cd));
$jsonData .= '"article'.$i.'":{"id":"'.$id.'","title":"'.$title.'","cd":"'.$cd.'"},';
}
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
}
?>
And mysqli table has an id, a title and a timestamp, I have tested the data in JSONLint and it's completely valid...Maybe some details that I give it's not necessary but nevermind... So it returns this error: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data ... var d = JSON.parse(x.responseText); Any help would be appreciated! Thanks in advance!
Found the problem..the problem was that my host provider send me some code together with my json response so the response from json was invalid..! Thank you for your feedback!

Categories