My div doesn't appear when I click on the submit button - javascript

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

Related

Why do my PHP sessions keep ending, and Apache occasionally crashes?

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.

How do I put document get element by id in a loop in javascript/php

How do I put 'txthint' in a loop using javascript? Like making them have differnt id's if i have more than 1 in the page. I think it's important if Im displaying different id's in hay.php
<html>
<head>
<script>
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>
</head>
</html>
<form>
<select name="users" onchange="showUser(this.value)">
<option>-None Selected-</option>
<?php
$con = mysqli_connect('localhost','root','','imetrics') or die ("Cannot connect");
$query=mysqli_query($con, "SELECT * FROM question");
while($row=mysqli_fetch_array($query)) {
?>
<option value="<?php echo $row["question_id"]; ?>"><?php echo $row["questiontitle"]; ?></option>
<?php
}
?>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
this is my php code in 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']);
}
}
?>

How to produce dynamic div id? in PHP/JAVASCRIPT/MYSQL

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 don't know how to display response text in multiple divs

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

Multiple selection listbox of State not displaying all Cities in another listbox(Php,mysql,ajax)

Selecting the Country dropdown displays State listbox with multiple selections without refreshing page . But selecting 2 or 3 States not displaying all cities in another lisbox. Cities are displaying for only one State. help
loadData.php
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','','test');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"test");
$sql="SELECT * FROM state WHERE country_id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<select name='try[]' onchange='showSecondUser(this.value)' multiple>";
while($row = mysqli_fetch_array($result)){
echo "<option value='".$row['id']."'>".$row['state_name']."</option>";
}
echo" </select>";
$g = $_GET['g'];
$sql="SELECT * FROM city WHERE state_id = '".$g."'";
$result = mysqli_query($con,$sql);
echo "<select name='try' multiple>";
while($row = mysqli_fetch_array($result)){
echo "<option value=''>".$row['city_name']."</option>";
}
echo" </select>";
mysqli_close($con);
?>
index.php
<html>
<head>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","loadData.php?q="+str,true);
xmlhttp.send();
}
function showSecondUser(str) {
if (str=="") {
document.getElementById("txtHint2").innerHTML="";
return;
}
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("txtHint2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","loadData.php?g="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select Country</option>
<option value="1">Australia</option>
<option value="2">Japan</option>
<option value="3">Russia</option>
<option value="4">Germany</option>
</select>
</form>
<br>
<div id="txtHint"></div>
<div id="txtHint2"></div>
</body>
</html>
It' because mysql query is wrong. You providing multiple numbers in a simple equal.
That should be:
$g = $_GET['g'];
$sql="SELECT * FROM city WHERE state_id IN (".$g.")";
$result = mysqli_query($con,$sql);
if $g is a comma separeted list of numbers.
If not you have to make it so.
So if $g is an array you have to do an implode() on it and than you can use it in the query
$g = $_GET['g'];
$g = implode(',', $g);
$sql="SELECT * FROM city WHERE state_id IN (".$g.")";
$result = mysqli_query($con,$sql);
if it is a string and lets say the numbers are separated my space than you replace space with comma:
$g = $_GET['g'];
$g = str_replace(' ', ',', $g);
$sql="SELECT * FROM city WHERE state_id IN (".$g.")";
$result = mysqli_query($con,$sql);
So in your case the MySQL query should be this:
$sql="SELECT * FROM state WHERE country_id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<select name='try[]' onchange='showSecondUser(this)' multiple>";
// there is a change here ^
while($row = mysqli_fetch_array($result)){
echo "<option value='".$row['id']."'>".$row['state_name']."</option>";
}
echo" </select>";
/*######################################################*/
$g = $_GET['g'];
$sql="SELECT * FROM city WHERE state_id IN (".$g.")";
$result = mysqli_query($con,$sql);
And the javascript should be this:
function showSecondUser(str){
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("txtHint2").innerHTML = xmlhttp.responseText;
}
}
var values = new Array();
for (var i=0; i < str.options.length; i++) {
cur = sel.options[i];
if (cur.selected) {
values.push(cur.value);
}
}
if (values.length) {
values = values.join(",");
} else {
values = null;
}
xmlhttp.open("GET","loadData.php?g="+values,true);
xmlhttp.send();
}

Categories

Resources