Ajax Request Works Fine, Javascript Does Not - javascript

I am looking for a solution to a problem I am having with this request.
function getProfile() {
if (str = "") {
document.getElementById("welcomebar").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("welcomebar").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST", "php/login.php?user="+document.getElementById("username").value, true);
xmlhttp.send();
}
}
That is my ajax code, and this is my php file which is a separate file.
<?php
$servername = "";
$user = "";
$pw = "";
$dbname = "";
$conn = new mysqli($servername, $user, $pw, $dbname);
if ($conn->connect_error) {
die("Could not connect to the server.");
}
$someone = $_GET["user"];
$sql = "SELECT * FROM some_table WHERE some_row='$someone'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Welcome, " . $row["some_row"]. "<span id='date'></span>
<script>
var date = new Date();
var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
document.getElementById('date').innerHTML = days[date.getDay()];
</script>
";
}
} else {
echo "Error";
}
?>
The ajax request is sending and receiving. When I log in as myself, the information I want it to display is being displayed properly. However, the java script code in the php file is not working when it is being received by the request. picture of the view source window.

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.

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. :/

AJAX and PHP/SQL Uncertainty over the location of a error

I am simply trying to update an element in an array, and the information, for whatever reason, doesn't seem to be getting through. Here is the javascript that sends the data:
var xmlhttp = new XMLHttpRequest();
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) {
// Do Nothing
}
}
xmlhttp.open("GET","updateGame.php?q=" + str + "&e=" + recordText,true);
xmlhttp.send();
Where recordText is declared elsewhere.
And this is the PHP that hopefully recieves the q and e:
<?php
$q = intval($_GET['q']);
$e = strval($_GET['e']);
$servername = "localhost";
$username = "*****";
$password = "*****";
$dbname = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE Games SET entries=$e WHERE PINs=$q";
$result = $conn->query($sql) or die($conn->error);
$conn->close();
?>
I have checked, and no information is being updated.
I fixed your Ajax file, here it is and it works fine, I also modified your PHP file to return the data just for testing purposes. Create two text files with the given names, copy-paste next codes and run from browser :
eli_davies_1.php
<html>
<head>
<script type="text/javascript">
function ajax_send ( a )
{ var ajax = false;
if ( window.XMLHttpRequest )
ajax = new XMLHttpRequest();
else if ( window.ActiveXObject )
ajax = new ActiveXObject( "Microsoft.XMLHTTP" );
if ( ajax )
{ var qq = document.getElementById( "txt_q" ).value; // DATA TO SEND.
var ee = document.getElementById( "txt_e" ).value; // DATA TO SEND.
ajax.open("GET","eli_davies_2.php?q=" + qq + "&e=" + ee ); // EXECUTE PHP.
ajax.onreadystatechange =
function ()
{ if ( ( ajax.readyState == 4 ) &&
( ( ajax.status == 0 ) ||
( ajax.status == 200 ) ) )
{ var d = document.getElementById( "div_result" );
d.innerHTML = ajax.responseText; // DISPLAY DATA RETURNED.
}
}
ajax.send( null );
}
}
</script>
</head>
<body>
<input type="text" id="txt_q" value="123" />
<br/>
<input type="text" id="txt_e" value="xyz" />
<br/>
<button onclick="ajax_send()">Send data</button>
<br/>
<div id="div_result"></div>
</body>
</html>
eli_davies_2.php
<?php
$q = intval($_GET['q']);
$e = strval($_GET['e']);
echo "Data received = >" . $q . "< and >" . $e . "<"; // DATA RETURNED (FOR TESTING ONLY).
/*
$servername = "localhost";
$username = "*****";
$password = "*****";
$dbname = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE Games SET entries=$e WHERE PINs=$q";
$result = $conn->query($sql) or die($conn->error);
$conn->close();
*/
?>

Receiving a responseText using xmlHttpRequest that i'm unsure about

I am using this code to add data to a database using ajax. Here is the html:
<form>
Product Name:</br>
<input type=text name=productName id="addProductName"></br>
Product Description:</br>
<input type=text name=productDescription id="addProductDescription"></br>
Product Quantity:</br>
<input type=number name=productQuantity id="addProductQuantity"></br>
<button id="addProduct" type=button>Add Product</button>
</form>
<div id="productAdded">test</div>
<script language="JavaScript" type="text/javascript" src="../javascript/test.js"></script>
Here is the javascript file test.js:
var xmlhttp;
function getXmlHttpRequest(){
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function addProduct(){
getXmlHttpRequest();
var productName = document.getElementById("addProductName");
var productDescription = document.getElementById("addProductDescription");
var productQuantity = document.getElementById("addProductQuantity");
var url = "insert.php?a=" + productName + "&b=" + productDescription + "&c=" + productQuantity;
xmlhttp.open("GET", url, false);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("productAdded").innerHTML = xmlhttp.responseText
}
};
}
var button;
button = document.getElementById("addProduct");
button.addEventListener("click", addProduct);
Here is the php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "products";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$productName = $_GET['a'];
$productDescription = $_GET['b'];
$productQuantity = $_GET['c'];
$sql = "INSERT INTO Product (ProductName, ProductDescription, ProductQuantity) VALUES ('$productName','$productDescription','$productQuantity')";
$conn->exec($sql);
echo 'Product ' . $productName . ' with quantity: ' . $productQuantity . ' Added';
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
I am getting all of the results that i expect except when i look at my database table i am seeing this instead of the data that was entered into the form:
[object HTMLInputElement]
When you do getElementById an HTMLInputElement is returned. After that you need to get the value of this element:
var productName = document.getElementById("addProductName").value;
var productDescription = document.getElementById("addProductDescription").value;
var productQuantity = document.getElementById("addProductQuantity").value;
You aren't actually getting the values from the input fields, use the value property to get it.
var productName = document.getElementById("addProductName").value;
var productDescription = document.getElementById("addProductDescription").value;
var productQuantity = document.getElementById("addProductQuantity").value;
also you should encode the date incase there ar any special characters in then
var url = "insert.php?a=" + encodeURIComponent(productName) + "&b=" + encodeURIComponent(productDescription) + "&c=" + encodeURIComponent(productQuantity);

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