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

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.

Related

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>

Grabbing part of a table from a database and displaying it on a website

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 :)

Json working for certain vars but not for others

I've made a script that requests information via Json. For some variables this works just fine, for others it doesn't.
When I use alert() for the variable neighbour1 it says the variable is undefined, when doing the same for the variables number and colour it works just fine.
This is the request script:
function getcolours() {
var hr = new XMLHttpRequest();
hr.open("GET", "camp_map_script.php", true);
hr.setRequestHeader("Content-type", "application/json");
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
for (var obj in data) {
number = data[obj].number;
colour = data[obj].colour;
neighbour1 = data[obj].n1;
alert (neighbour1);
window["colour" + number] = colour;
var x = document.getElementsByClassName(number + ' ' + colour);
x[0].style.display = "block";
}
}
}
hr.send(null);
}
This is the php part:
<?php
include_once("../php_includes/check_login_status.php");
?><?php
$number = "";
$sql = "SELECT camp_id FROM users WHERE username='$log_username'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_row($query);
$campid = $row[0];
$sql = "SELECT players FROM campaigns WHERE id='$campid'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_row($query);
$players = $row[0];
$number = ($players*2)-1;
$sql = "SELECT number, colour, player, n1, n2, n3, n4, n5, n6, n7, n8 FROM lands WHERE camp_id='$campid' ORDER BY number";
$query = $connect->query($sql);
$jsonData = '{';
if ($query->num_rows > 0) {
while($row = $query->fetch_assoc()) {
$jsonData .= '"obj'.$row["number"].'":{"number":"'.$row["number"].'", "colour":"'.$row["colour"].'", "player":"'.$row["player"].'", "n1":"'.$row["n1"].'"},';
}
}
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
$connect->close();
?>
Also when I check the php document the variable n1 is echoed correctly. So the error must be on the java script side or the transit.
It is probably something stupid that I'm overlooking but I just don't see it. I've copy pasted the working parts and changed them to work with other variables but it still doesn't work. :/

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

Categories

Resources