I am making a quiz website ,on click it get questions and options from database
in a row.I want to display question in one div and options in other 3 divs.
i have two pages for it one is careerguidance.php and one is getquestion.php.
Careerguidance.php
<head>
<script>
var str=0;
function showquestion() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("div1").innerHTML = xmlhttp.responseText;
// document.getElementById("dop1").innerHTML = xmlhttp.responseText;
// document.getElementById("dop2").innerHTML = xmlhttp.responseText;
// document.getElementById("dop3").innerHTML = xmlhttp.responseText;
}
}
str++;
xmlhttp.open("GET","getquestion.php?idd="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<button onClick="showquestion()">Next</button>
<div class='quiz' id='div1'><h2>$question</h2></div>
<div class='quizoption' id='dop1' onClick=''><h4></h4></div>
<div class='quizoption' id='dop2' onClick=''><h4></h4></div>
<div class='quizoption' id='dop3' onClick=''><h4></h4></div>
</body>
getquestion.php
<?php
$idd = intval($_GET['idd']);
require_once('db_con.php');
//$sq="select id from questions";
//$q_id = (isset($_GET['id']) ? intval($_GET['id']) : 1);
//static $r=1;
//static $q_id=0;
//$q_id++;
$sql="SELECT * FROM questions where id= '".$idd."'";
//$sql="SELECT * FROM questions WHERE id =$r";
$result = mysql_query($sql);
/*
echo "<table>
<tr>
<th>Question</th>
<th>Option1</th>
<th>Option2</th>
<th>Option3</th>
<th>Next</th>
</tr>";
*/
while($row = mysql_fetch_array($result)) {
// echo "<tr>";
echo "<h2>";
echo $row['question'];
echo "</h2>" ;
// echo "<br>" . $row['option1'] ;
// echo "<td>" . $row['option2'] . "</td>";
// echo "<td colspan='2'>" . $row['option3'] . "</td>";
// echo "</tr>";
}
//echo "</table>";
mysql_close($conn);
?>
</body>
</html>
You need to parse your response in parts and then assign values to specific divs. E.g. if your xmlhttp.responseText` looks like this:
{
"question": "Who is it?",
"answers": ["Merry", "Billy", "Joe"]
}
you will something like this:
function buildQuestionaree(data) {
//
// if data is a string
// data = JSON.parse(data);
//
var question = data.question;
var answers = data.answers;
document.getElementById("div1").innerHTML = question;
document.getElementById("dop1").innerHTML = answers[0];
document.getElementById("dop2").innerHTML = answers[1];
document.getElementById("dop3").innerHTML = answers[2];
}
Related
I have a input text field i get the data from database using javascript and php.
get.html get the data by javascript
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","get.php?q="+str,true);
xmlhttp.send();
}
}
<input type="text" id="name" onblur="showUser(this.value)">
<input type="buton" name="">
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
get.phpto connect database to show data
<?php
$q = intval($_GET['q']);
$con=mysql_connect("localhost","root","") or die("Could not Connect with Sql");
mysql_select_db("dialog",$con) or die("Could connect to Database");
$sql="SELECT * FROM customer WHERE cx_number = '".$q."'";
$result = mysql_query($sql);
echo "<table>
<tr>
<th>cx_number</th>
<th>package</th>
<th>balance</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['cx_number'] . "</td>";
echo "<td>" . $row['package'] . "</td>";
echo "<td>" . $row['balance'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
now my question is how to show the button to increase package amount if package balance is zero
If you need it for each user just replace in get.php
echo "<td>" . $row['balance'] . "</td>";
to
echo "<td>" . $row['balance'] ;
if ($row['balance'] <= 0) echo "<button>Your button </button>";
echo "</td>";
You also can do it on browser side. Add after
document.getElementById("txtHint").innerHTML = this.responseText;
code like this
$("#txtHint tr").each(function() { // cicle through each row
el=$this.find( "td:eq(2)" ) // get td with index==2.(firs==0, secon==1)...
if (parseFloat(el.html()<=0) { // check if it's 0 or lower
el.append( $( "Your button or link html here" ) ); // add button
}
});
you can change it in your div like this :
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","get.php?q="+str,true);
xmlhttp.send();
}
}
<input type="text" id="name" onblur="showUser(this.value)">
<div id="txtHint">
<b>Person info will be listed here...</b></div>
in your ajax file :
<?php
$q = intval($_GET['q']);
$con=mysql_connect("localhost","root","") or die("Could not Connect with Sql");
mysql_select_db("dialog",$con) or die("Could connect to Database");
$sql="SELECT * FROM customer WHERE cx_number = '".$q."'";
$result = mysql_query($sql);
echo "<table>
<tr>
<th>cx_number</th>
<th>package</th>
<th>balance</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['cx_number'] . "</td>";
echo "<td>" . $row['package'] . "</td>";
echo "<td>" . $row['balance'] . "</td>";
echo "<td>". if( $row['balance'] == 0) { '<input type="button" name="" value="your value"> } '. "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
My JavaScript:
//Function that gets the chat from backend
function showmessage(str) {
if (str == "") {
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("chat").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","/backend-display.php?q="+str,true);
xmlhttp.send();
}
}
//Show any messages that will pop-up
setInterval('showmessage()',400);
//Function that updates new rows
function newrows(str) {
if (str == "") {
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = this.responseText;
var elem = document.getElementById('chat');
elem.scrollTop = elem.scrollHeight;
}
};
xmlhttp.open("GET","/test2.php?success=true"+str,true);
xmlhttp.send();
}
}
//Updates new rows every x seconds
setInterval('newrows()',300);
//Backend to send a message
function loadDoc() {
var xhttp = new XMLHttpRequest();
var mes = document.getElementById("message").value;
var message = "message=" +mes;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("input").innerHTML = this.responseText;
}
};
xhttp.open("POST", "/backend-input.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(message);
document.forms["form"].reset();
}
PHP.ini config:
Php.ini config link
Backend for inputting:
<?php include 'auth.php';?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$name = $_SESSION["name"];
$messageunfilter = $_POST["message"];
$con = mysqli_connect('localhost','root','','chat');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
if(empty($_POST["message"])){
echo "You must enter a message...";
exit();
}else{
echo "success";
}
//Checking SQL
$check = array("\\", "'");
$change = array("\\\\", "''");
$messagefilter = str_replace($check, $change, $messageunfilter);
date_default_timezone_set('Europe/London');
$current_date = date("Y-m-d H:i:s");
mysqli_select_db($con,"ajax_demo");
$sql="INSERT INTO `chat` (`id`, `username`, `message`, `date`) VALUES (NULL, '$name', '$messagefilter', '$current_date')";
$result = mysqli_query($con,$sql);
mysqli_close($con);
?>
</body>
</html>
Backend for recieving messages from DB:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<head>
<link href="style.css" rel="stylesheet">
</head>
<?php //Selects all of the logged in users messages.
$name = $_SESSION["name"];
$con = mysqli_connect('localhost','root','','chat');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM `chat` ORDER BY date";
$result = mysqli_query($con,$sql);
$numrows = mysqli_num_rows($result);
if( $numrows == "0" or !isset($_SESSION["name"])){
echo "<div class='msg'>";
echo "<div class='username_admin'>System</div>";
echo "<div class='msg_admin'>There are no messages to display...</div>";
echo "</div>";
exit();
}else{
echo "";
}
echo "<div class='msg_container'>";
while($row = mysqli_fetch_array($result)) {
$class_msg = "msg";
$class_username = "username";
$class_message = "message";
if ($row['username'] == $_SESSION['name']) {
$class_msg = "msg_user";
$class_username = "username_user";
$class_message = "message_user";
}
echo "<div class='$class_msg'>";
echo "<div class='$class_username'><span>" . $row['username'] . "</span></div>";
echo "<div class='$class_message'><span>" . $row['message'] . "</span></div>";
echo "</div>";
}
echo "</div>";
mysqli_close($con);
?>
</body>
</html>
I am aware of websockets and my code needs to be cleaned up a lot, as well as the fact that my statements are not prepared.
For some reason after this system running for 5 minutes or so, the sessions seem to get destroyed?
I have no idea why this is? Is it because I am requesting it too many times?
Even if I have just 2 users connected messaging each other it still crashes, it can crash after 60 seconds, 1 minute?
Can someone please help me figure out why this is, I would be more than grateful.
Thank you so much for even looking at this post, even that means a lot! (Sorry for the overload of code here, I just want to be sure that I am showing you everything I can!)
According to the comments at the php docs for session_start() (http://php.net/manual/en/function.session-start.php), it may be necessary to write to the session data in order to keep the session alive under some circumstances.
I would give adding $_SESSION['time'] = time(); after your session_start()s a try and see if that helps. I'm not sure what is causing the crash but I would check the apache error logs first.
I have an ajax code that displays data from table columns when a data is chosen from the dropdown.
surveycontent.php
<script type="text/javascript">
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","hay.php?q="+str,true);
xmlhttp.send();
}
}
</script>
ajax.php. I have a textbox that generates dropdowns based on how many the user input
if($question !="" && $cnt!="" && $addQues!="yes" && $main == 1){
$i = 0;
for ($i = 1; $i <= $cnt; $i++)
{
$query=mysqli_query($con, "SELECT question.* FROM question LEFT JOIN category AS subcategory on subcategory.category_id = question.question_subcat WHERE question.question_category = $question AND (question.question_subcat IS NULL OR subcategory.category_id IS NOT NULL)");
echo "<form><b id='labelquestion_dropdown'>Question #". $i."</b>";
echo "<select id='question_dropdown".$i."' class='form-control' onchange='showUser(this.value)' style='width: 300px;' name='question_dropdowns".$i."'>";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
}
echo "</select></form>";
echo "<div id='txtHint'><b>Person info will be listed here...</b></div>";
echo "<br />";
}
echo "<div id='insertQuesHere".$i."'></div>";
echo "<a href='#add_question' onclick='return addQues_Cat();'>Add Question</a> | ";
echo "<a href='#del_question' onclick='return delQues();'>Delete Question</a>";
}
hay.php
<?php
$con = mysqli_connect('localhost','root','','imetrics') or die ("Cannot connect to database");
if(!$con){
echo ('Could not connect: ' . mysqli_error($con));
}
$id= isset($_GET["q"])?intval($_GET["q"]):"";
$query = mysqli_query($con, "SELECT * FROM question WHERE question_id = '".$id."'");
function displayOption($i, $value, $answer_type) {
if($value == null) {
return;
}
if($answer_type == "radiobutton") {
echo '<input type="radio" name="rinput" value="'.htmlspecialchars($value, ENT_QUOTES).'">'.htmlspecialchars($value).'<br>';
} else if($answer_type == "checkbox") {
echo '<input type="checkbox" name="cinput['.$i.']" value="'.htmlspecialchars($value, ENT_QUOTES).'">'.htmlspecialchars($value).'<br>';
}
}
while($row = mysqli_fetch_assoc($query)) {
for($i = 1; $i<=10; ++$i) {
displayOption($i, $row["Option_$i"], $row['answer_type']);
}
}
?>
I have a textbox that generates dropdowns based on the user input. For example, I generated 3 dropdowns, I need to make it possible that hay.php will display data for each of the dropdowns when clicked. Atm it's only showing 1 whichever dropdown I use to choose from. I think the problem is I only have 1 id for the <div id='textHint'> or is it a different problem?
One "hacky" way you could do this ( if I understood the problem correctly ) would be to assign a unique id to the various generated DIV elements and supply that ID as a second argument to your ajax function.
/* note 2nd parameter - id */
function showUser(str,id) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
/* use id supplied */
document.getElementById(id).innerHTML = this.responseText;
}
};
xmlhttp.open("GET","hay.php?q="+str,true);
xmlhttp.send();
}
}
And the PHP code
for( $i = 1; $i <= $cnt; $i++ ){
$query=mysqli_query($con, "SELECT question.* FROM question LEFT JOIN category AS subcategory on subcategory.category_id = question.question_subcat WHERE question.question_category = $question AND (question.question_subcat IS NULL OR subcategory.category_id IS NOT NULL)");
echo "
<form>
<b id='labelquestion_dropdown'>Question #{$i}</b>
<select id='question_dropdown{$i}' class='form-control' onchange=\"showUser( this.value, 'txtHint{$i}' )\" style='width: 300px;' name='question_dropdowns{$i}'>
<option selected>Select";
while($row=mysqli_fetch_array($query)){
echo "<option value='{$row['question_id']}'>" . $row["questiontitle"];
}
echo "
</select>
</form>
<div id='txtHint{$i}'><b>Person info will be listed here...</b></div>
<br />";
}
You might notice the missing </option> from the above - it's not necessary to use it so I tend to omit it.
Okay! If You wanna to put your div in Drop-down.
You may try this in Your code
echo "<option class="HINT"><div id='txtHint'><b>Person info will be listed here...</b></div></option>";
<select>
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option><div>THIS IS DIV</div></option>
</select>
I would like to create a poll and show the results when this one is completed. But, the answers don't appear...
Here is my page1.php:
<div id="poll">
<?php
echo "<form onsubmit='getVote(option_ID); return false;' >" ;
echo "<p><b> $question_content </b></p>" ;
$poll_option_selection = "SELECT option_ID, option_content FROM poll_options WHERE question_ID='$question_ID'" ;
$poll_option_result = mysqli_query ($connect,$poll_option_selection) ;
foreach ($poll_option_result as $poll_option) {
$option_ID = $poll_option ['option_ID'] ;
$option_content = $poll_option ['option_content'] ;
?><script type="text/javascript">var option_ID = <?php echo json_encode($option_ID) ; ?> ;</script><?php
echo "<input type='radio' id='$option_ID' value='option' required' /> $option_content</br>" ;
}
echo "<p><input type='submit'></p></form>" ;
?>
</div>
<script type="text/javascript">
var user_ID = <?php echo json_encode($user_ID) ; ?> ;
function getVote(option_ID) {
var option_ID = document.querySelector("input[value='option']:checked").id;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (option_ID.readyState==4 && option_ID.status==200) {
document.getElementById("poll").innerHTML=option_ID.responseText;
}
}
xmlhttp.open("GET","./core/vote.php?user_ID="+user_ID+"&option_ID="+option_ID,true);
xmlhttp.send();
}
</script>
And here is page2.php with the results, called by getVote(option_ID):
<?php
echo "<p><b> $question_content </b></p>" ;
$option_selection = "SELECT option_content, option_score FROM poll_options WHERE question_ID='$question_ID' ORDER BY option_score DESC" ;
$option_result = mysqli_query ($connect,$option_selection) ;
foreach ($option_result as $option) {
$option_content = $option ['option_content'] ;
$option_score = $option ['option_score'] ;
echo "
<table>
<th><td> $option_content : </td>
<td><b> $option_score votes </b></td></th>
</table>
" ;
}
echo "<p>Vous devez attendre 6 heures afin de pouvoir revoter</p>" ;
?>
Could someone explain the error to me with an example please? Because I am a beginner... Thank you.
You're checking a string, the elements ID, for it's readyState, which won't work, you'd have to check the XMLHttpRequest object instead.
Here's really what you're doing
function getVote(option_ID) {
var option_ID = document.querySelector("input[value='option']:checked").id;
xmlhttp.onreadystatechange = function() {
if ( option_ID.readyState == 4 && option_ID.status == 200 ) {
// ^ THATS A STRING ?
}
What you want to do is
var user_ID = <?php echo json_encode($user_ID) ; ?>;
function getVote(option_ID) {
var option_ID = document.querySelector("input[value='option']:checked").id;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("poll").innerHTML = xmlhttp.responseText;
}
}
var data = "?user_ID=" + encodeURIComponent(user_ID) +
"&option_ID=" + encodeURIComponent(option_ID);
xmlhttp.open("GET", "./core/vote.php" + data, true);
xmlhttp.send();
}
I want to grab part of a table from a database called "TKACONT".
When a user clicks the button that executes the tkakata() function I am grabbing the Firstname, Lastname , and kata (points), then displaying them into a table.
I display the table, sorted from highest to lowest points, in a <div> with the ID displayrank.
Here is the code:
kataajax.js
function tkakata(){
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlHttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(!xmlHttp)
alert("Something went wrong")
else
return xmlHttp
}
function process(){
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
xmlHttp.open("GET", "tkakatagrab.php", true)
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()',1000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("displayrank").innerHTML = message;
setTimeout('process()',1000);
}
else
{
alert("Database not connecting!")
}
}
}}
tkakatagrab.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
$con = mysqli_connect('MY_SERVER_IP','USERNAME','PASSWORD','TKACONT');
if(!$con){
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT Firstname,Lastname,Kata FROM Contestant ORDER BY Kata DESC";
$result = mysqli_query($con,$sql);
echo '<response>';
echo "<table>
<tr>
<th>Points</th>
<th>Firstname</th>
<th>Lastname</th>";
//while loop right here
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Kata'] . "</td>";
echo "<td>" . $row['Firstname'] . "</td>";
echo "<td>" . $row['Lastname'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo '</response>';
mysqli_close($con);
?>
This part of your query:
ORDER BY Kata DESC
orders the results from highest to lowest (ie: DESCending), change the DESC to ASC (ASCending) if you want the reverse order (lowest to highest).
Hope this helps :)