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

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();
*/
?>

Related

Parse returned 2D-Array from PHP-Script to Javascript-Variable inside a Wordpress-Codeblock

So I have a standard php-script, which is stored in an external php-file that is located on the server in the main folder (in this case /html/mysite/getlocations.php).
<?php
function getData() {
// MySQL-Connection-Variables
$servername = "xxxxxxxxxx.hosting-data.io";
$username = "xxxxxxxxxxxxxxxxxx";
$password = "xxxxxxxxxxxxxx";
$dbname = "xxxxxxxxxxxx";
// Create connection
$conn = mysqli_connect( $servername, $username, $password, $dbname );
$conn_number = mysqli_connect( $servername, $username, $password, $dbname );
// Check connection
if ( !$conn ) {
die( "Connection failed: " . mysqli_connect_error() );
}
// SQL-Query for Locations
$sql = "SELECT ID, Beschreibung, Straße, Hausnummer, PLZ, Ort, Bezirk, Leiter, Email, Telefon, Website FROM Locations";
//SQL-Query for Number of Entries
$sql_number = "SELECT COUNT(*) FROM Locations;"
$result = mysqli_query( $conn, $sql );
// Size of MySQL-Table
$size = mysqli_query( $conn_number, $sql );
$counter = 0;
// 2D-Array with all the needed informations for further processing
$returnarray = array();
// Number of Table-Entries > 0
if ( mysqli_num_rows( $result ) > 0 ) {
// Iterate over all Entries
while ( $row = mysqli_fetch_assoc( $result ) ) {
$desription = $row[ "Beschreibung" ];
$street = $row[ "Straße" ];
$number = $row[ "Hausnummer" ];
$plz = $row[ "PLZ" ];
$city = $row[ "Ort" ];
$bezirk = $row[ "Bezirk" ];
$leiter = $row[ "Leiter" ];
$email = $row[ "Email" ];
$phone = $row[ "Telefon" ];
$website = $row[ "Website" ];
$returnarray[$counter] = array();
$returnarray[$counter]['name'] = $desription;
$returnarray[$counter]['street'] = $street;
$returnarray[$counter]['number'] = $number;
$returnarray[$counter]['plz'] = $plz;
$returnarray[$counter]['city'] = $city;
$returnarray[$counter]['bezirk'] = $bezirk;
$returnarray[$counter]['leiter'] = $leiter;
$returnarray[$counter]['email'] = $email;
$returnarray[$counter]['telefon'] = $telefon;
$returnarray[$counter]['website'] = $website;
$counter = $counter + 1;
}
}
// Close connection
mysqli_close( $conn );
return $returnarray;
}
echo getData();
?>
This php-scripts connects to a mysql-database, fetches information and stores it in a twodimensional array.
Now I want to retrieve this returned array and put it in a javascript-variable, so I can use it for further processing inside a Wordpress-Codeblock.
So my attempt was this:
<script type="text/javascript">
var data_from_ajax;
$.get('/html/mysite/getlocations.php', function(data) {
data_from_ajax = data;
});
</script>
But this didnt work like I intended it would.
You can create a JSON string using PHP's built-in json_encode function and parse it in JS with JSON.parse.
I don't think you can pass variables directly to Javascript without serialization.

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.

Ajax Request Works Fine, Javascript Does Not

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.

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

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

Categories

Resources