JavaScript HttpRequest always return the same results - javascript

I have a HTML page JavaScript which send a GET request data to PHP file to return all datas saved in the database . PHP replies with a HTML-table - that works fine!
But: When if i click a button (which calls the same JavaScript function) to update my table in order to display the new data, i get the same result (and i have definitely new data on table).
If I call the PHP manually via the browser it'll show me the new results immediately and at this moment it is also working with JavaScript (but only once).
Here is a part of my code.
HTML/JS:
<button onclick="GetData()"></button>
<div id="test"></div>
<script>
function GetData(){
var xhttp = new XMLHttpRequest();
document.getElementById("test").innerHTML = "";
xhttp.onreadystatechange = function(){
if (xhttp.readyState == 4 && xhttp.status == 200){
document.getElementById("test").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "../GetData.php", true);
xhttp.send();
}
</script>
PHP:
//DB details
$dbHost = 'localhost';
$dbUsername = 'lalalala';
$dbPassword = 'lalalalal';
$dbName = 'lalalala';
//Create connection and select DB
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName) or die ("UUUUPS");
$sql = "select name, beschreibung, image, video from data";
$result = $db->query($sql);
if ($result->num_rows > 0) {
$return = '<table class ="table table-hover"><thead><tr><th scope="col">Name</th><th scope="col">Beschreibung</th><th scope="col">Bilddatei</th><th scope="col">Video-Url</th></tr></thead><tbody>';
// output data of each row
while($row = $result->fetch_assoc()) {
$return .= "<tr><td>".$row["name"]."</td><td>".$row["beschreibung"]."</td><td><img src=data:image/png;base64,".base64_encode($row["image"])."/></td><td>".$row["video"]."</tr>";
}
$return .= "</tbody></table>";
$db->close();
echo $return;
} else {
echo "0 results";
}
Thank you for your help!

It seems your browser is caching your result, that's why you see data.
You can test it like this:
var random = Math.floor(Math.random() * 100);
xhttp.open("GET", "../GetData.php?"+random, true);
If this helps, look into expire headers in your PHP script. Also, the way you're doing queries in quite outdated. It's a very PHP4 way. Have a look here: http://php.net/manual/en/book.mysqli.php

I guess you probably know this, but just in case. Have you had a look in your browsers inspector, when testing you html page? especially the network tab within that inspector. There you can see the actual response from the server and you can see if it is served from cache or fetched (you can even disable cache there), maybe this helps.
Kind regard,
Mark

Related

Securely communicate with mysql server (MariaDB) using javascript and php (NO jQuery)

I am trying to achieve two things:
(1) Get text from a contenteditable div, use javascript to send that text to php, use php to send that data to a MySQL database and save it
(2) retrieve the saved data/text and reinsert it into a contentedtiable div
All of this whilst NOT using jQuery
What I've got so far:
index.html
<body>
<div contenteditable="true" id="editable"></div>
<button onClick="send_data();">Save text</button>
<button onClick="retrieve_data();">Get text</button>
</body>
javascript.js
function send_data() {
var php_file = "connection.php";
var http_connection = new XMLHttpRequest();
http_connection.open("POST", php_file, true);
http_connection.onreadystatechange = function() {
if(http_connection.readyState == 4 && http_connection.status == 200) {
alert(http_connection.responseText);
}
}
http_connection.send(document.getElementById('editable').innerText);
}
function retrieve_data() {
// I do not know what to put here
}
connection.php
<?php
$servername = "localhost";
$username = "mysql_user";
$password = "secure_password";
$dbname = "some_database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
if(!conn) {
echo 'No connection';
}
if(!mysqli_select_db($conn,'some_database')) {
echo "No database";
}
$some_val = $_GET['text']
$sql = "SELECT text FROM some_database";
$result = $conn->query($sql);
echo $result;
$conn->close();
?>
Edit: what my code fails to do is to upload text as well as recieve text.
Some problems in the js:
http_c is not defined
readyState is spelled incorrectly
the send method needs to be outside the onreadystatechange callback
Once those things are corrected, program should give different, which is not to say expected, result.
Other things:
The js is sending a 'POST' request. The php is looking for $_GET["text"] which will give undefined error. I'm speculation this $sql = "SELECT text FROM some_database"; will fail (if it reaches that line) unless there is a table in the database named "some_database".
Suggest, for starters, get the ajax working by short-circuiting the code in connection.php to something like
echo "You are here";
exit;
Then gradually working forward between the js and the php until programs give you what you want.

Posting Data to a database through javascript Ajax which calls a php page

So basically I want to have a Javascript function that posts data to a table in my database. i know that I need to call a php page to do this. But the code I have written doesn't work. The js fucntion is triggered by a button press in html. I need to do this in js ajax and not jquery ajax
The Javascript
function comment_sub(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
}
};
xhttp.open("POST", "static/setcomments.php", true);
xhttp.send(encodeURIComponent(document.getElementById('comment-textbox').value));
}
The PHP
<?php
echo "Hello";
$mydb = mysqli_connect("localhost", "root","", "website");
if (!$mydb){
die("Connection failed".mysqli_connect_error());
}
$sql = "INSERT INTO 'comments'('comment_text') VALUES ('{$_GET['comment-textbox']}')";
$query = mysqli_query($mydb, $sql);
if (!$query)
{
die('Error: ' . mysql_error());
}
echo "1 record added"
?>
Checked the network and console log. The JS function is being called fine but the network logs gives me a 404 error for the post request
You are only sending the value itself, not the name comment-textbox.
Try this:
xhttp.send(JSON.stringify({
'comment-textbox': document.getElementById('comment-textbox').value
}));
On the PHP page, you are doing a HTTP POST and not a HTTP GET. So rewrite it as this:
$sql = "INSERT INTO 'comments'('comment_text') VALUES ('{$_POST['comment-textbox']}')";

Session variable not being updated after being used

I am trying to check the result from a function and determine where on my page it should go by using the Session Variable "alernativeRD". It goes to the correct element on the first try, but after that it keeps going only to the first element regardless of whether its right or not. After some testing I've found that "alernativeRD" does get changed every time in the PHP function, but it doesn't change in the Javascript part.
PHP PART
function firstSignInDefault(){
global $con;
$clubUsername= $_SESSION['clubUsername'];
$_SESSION['alternativeRD']='false'; //sets it back to false to avoid having alternativeRD be true for next user
$lastName= mysqli_real_escape_string($con, $_POST['lastNameF']);
$firstName= mysqli_real_escape_string($con, $_POST['firstNameF']);
$memberID= mysqli_real_escape_string($con, $_POST['idNumberF']);
if(!(is_numeric($memberID))){
die("<h3> Student ID must be a number </h3>");
}
$getMemberRow= mysqli_query($con, "SELECT * FROM memberstable WHERE MemberMadeID='$memberID' AND Club='$clubUsername'");
if(mysqli_num_rows($getMemberRow)==0){
$sql="INSERT INTO memberstable (MemberMadeID,FirstName,LastName,Club)
VALUES ('$memberID','$firstName','$lastName', '$clubUsername')";
$test=false; //checks to make sure sql statement runs fine
if(mysqli_query($con,$sql))
$test=true;
else {
echo "<h3> Error running sql </h3>";
}
$date=date("Y-m-d h:i:sa");
$getMemberRow= mysqli_query($con, "SELECT * FROM memberstable WHERE MemberMadeID='$memberID' AND Club='$clubUsername'");
$memberRowArray=mysqli_fetch_array($getMemberRow);
$memberPanID=$memberRowArray['UniquePanDBID'];
$sql2="INSERT INTO signinstable (TimeOfSignIn, UniquePanDBID, ClubUsername, FirstName, LastName) VALUES ('$date','$memberPanID','$clubUsername', '$firstName', '$lastName')";
//THE FOCUS OF THIS QUESTION IS BELOW THIS COMMENT
if(mysqli_query($con, $sql2) && $test==true){
$_SESSION['alternativeRD']='true';
echo " <h2 id='signedInPeople' >".$date. " ".$firstName ." ". $lastName ."</h2>";
}
}
else {
echo "<h3> ID Number already in use</h3>";
}
}
JAVASCRIPT/AJAX PART
function processFSIF(){
var xmlHttp= makeXMLHTTP();
// Create some variables we need to send to our PHP file
var url = "signInDataPlace.php";
var idNumberF = document.getElementById("idNumberF").value;
var lastNameF = document.getElementById("lastNameF").value;
var firstNameF = document.getElementById("firstNameF").value;
var typeSignIn="first";
var vars = "idNumberF="+idNumberF +"&lastNameF="+lastNameF +"&firstNameF="+firstNameF +"&typeSignIn=" +typeSignIn;
xmlHttp.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var return_data = xmlHttp.responseText;
//AREA OF PROBLEM BELOW
<?php
if($_SESSION['alternativeRD']=='true'){ ///YOU ARE HERE, alternativeRD is acting stupid
?>
document.getElementById("serverInputList").innerHTML = return_data;
<?php
}else{
?>
document.getElementById("serverInputFSIF").innerHTML = return_data;
<?php
}
?>
}
}
// Send the data to PHP now... and wait for response to update the status div
xmlHttp.send(vars); // Actually executes the request
document.getElementById("serverInputFSIF").innerHTML = "processing...";
}
Your Javascript was printed only once, before you use AJAX. You can return the session value together with response, or you can set the cookie in PHP, than use it in javascript.

Trouble with php variables and ajax javascript

ok I have edited this to another couple of questions I've asked on a similar issue, but I really am in a rush so thought I'd start a new one, sorry if it bothers anyone.
first I have a php script on test.php on the apache server
<?php
//create connection
$con = mysqli_connect("localhost", "user", "password", "dbname");
//check connection
if (mysqli_connect_errno()){
echo "failed to connect to MySQL: " . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
?>
Then I've got this ajax script set to fire onload of page a webpage written in html. so the load() function is onload of the page in the body tag. This script is in the head.
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = "<?php echo $n1;?>;
}
}
}
ok so what I want is the $n1 variable in the php script to be used in the javascript ajax code. Where the script is, but I'm not sure where or how to make use of the variable, I've tried a few things. All that happens right now is the innerHTML of itemNameLink1 just disappears.
I'm quite new so any advise would be appreciated, thanks.
The response (this is what you echo in php) returned from request you can get by responseText attribute of XMLHttpRequest object.
So first your JS code should be:
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = xmlhttp.responseText;
}
}
}
now in php echo $n1 variable:
....
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
// echo it to be returned to the request
echo $n1;
Update to use JSON for multiple variables
so if we do this:
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$response = array
(
'name' => $name,
'color' => $color,
'price' => $price
);
echo json_encode($response);
Then in javascript we can parse it again to have data object containing 3 variables.
var data = JSON.parse(xmlhttp.responseText);
//for debugging you can log it to console to see the result
console.log(data);
document.getElementById("itemNameLink1").innerHTML = data.name; // or xmlhttp.responseText to see the response as text
Fetching all the rows:
$row = mysqli_fetch_array($grab); // this will fetch the data only once
you need to cycle through the result-set got from database: also better for performance to use assoc instead of array
$names = $color = $price = array();
while($row = mysqli_fetch_assoc($grab))
{
$names[] = $row['name'];
$color[] = $row['color'];
$price[] = $row['price'];
}
$response = array
(
'names' => $names,
'color' => $color,
'price' => $price
);
You can dynamically generate a javascript document with php that contains server side variables declared as javascript variables, and then link this in the head of your document, and then include this into your document head whenever server side variables are needed. This will also allow you to dynamically update the variable values upon page generation, so for example if you had a nonce or something that needs to change on each page load, the correct value can be passed upon each page load. to do this, you need to do a few things. First, create a php script and declare the correct headers for it to be interpreted as a script:
jsVars.php:
<?php
//declare javascript doc type
header("Content-type: text/javascript; charset=utf-8");
//tell the request not to cache this file so updated variables will not be incorrect if they change
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Pragma: no-cache'); // HTTP 1.0.
header('Expires: 0'); // Proxies.
//create the javascript object
?>
var account = {
email: <?= $n1; ?>,
//if you need other account information, you can also add those into the object here
username: <?= /*some username variable here for example */ ?>
}
You can repeat this for any other information you need to pass to javascript on page load, and then reference your data using the namespaced javascript object (using object namespacing will prevent collisions with other script variables that may not have been anticipated.) wherever it is needed as follows:
<script type="text/javascript>
//put this wherever you need to reference the email in your javascript, or reference it directly with account.email
var email = account.email;
</script>
You can also put a conditional statement into the head of your document so it will only load on pages where it is needed (or if any permission checks or other criteria pass as well). If you load this before your other scripting files, it will be available in all of them, provided you are using it in a higher scope than your request.
<head>
<?php
//set the $require_user_info to true before page render when you require this info in your javascript so it only loads on pages where it is needed.
if($require_user_info == TRUE): ?>
<script type="text/javascript" href="http://example.com/path-to-your-script/jsVars.php" />
<?php endif; ?>
<script type="text/javascript" href="your-other-script-files-that-normally-load" />
</head>
You can also do this for any other scripts that have to load under specific criteria from the server.
You should define the PHP variable. And use that variable in your javascript:
<?php
$n1 = "asd";
?>
<html>
<head></head>
<body>
<div id="itemNameLink1"></div>
<script>
function load()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '/test.php', true);
xmlhttp.send(null);
//Note you used `onreadystatecahnge` instead of `onreadystatechange`
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("itemNameLink1").innerHTML = '<?=$n1?>';
}
}
}
load();
</script>
</body>
</html>

xmlHttp2 function (var params coding needed!)

In this page where this code is,there is a form of 3 details
country,gender,topic
So the idea is to send these 3 details to startChat.php and so that the php can extract the 3 details.
The code is as below
function startChat()
{
xmlHttp2 = GetXmlHttpObject();
if (xmlHttp2 == null)
{
alert("Browser does not support HTTP Request");
return;
}
var url = "startChat.php";
var params = "country,gender,topic";<<<<<<<<<<<<<<<<<<<<<<<what coding this should be?????
xmlHttp2.open("GET", url, true);
xmlHttp2.send(params);<<<<<<<<is this correct?????
xmlHttp2.onreadystatechange = stateChanged2;
}
And also i would need help with the startChat.php part
<?php
include('config.inc.php');
$preference="$_GET[params]";<<<<<<<<<<<<<<<<<<<<<<<<<<<<what coding this should be????????????????????????????????????
include('database.inc.php');
mysql_query("INSERT INTO users (inchat,preference) values('N','$preference')");
echo mysql_insert_id();
mysql_close($con);
?>
Please help,asking sincerely :(
First off, you ought to use a POST request instead of a GET, because it's clear from your code that this request is supposed to change state on the server.
Your params variable should be form encoded. You can do this with encodeURIComponent, like so:
var params = 'country=' + encodeURIComponent(userCountry) +
'&gender=' + encodeURIComponent(userGender) +
'&topic=' + encodeURIComponent(userTopic);
Second, you ought to sanitize the data before you insert it into your DB. Otherwise you expose yourself to SQL injection attacks.
<
?php
include('config.inc.php');
// need to create db connection before mysql_real_escape_string is called
include('database.inc.php');
$country = mysql_real_escape_string($_POST['country'], $con);
$gender = mysql_real_escape_string($_POST['gender'], $con);
$topic = mysql_real_escape_string($_POST['topic'], $con);
mysql_query("
INSERT INTO users(inchat, country, gender, topic)
VALUES('N','$country', '$gender', '$topic')
");
echo mysql_insert_id();
mysql_close($con);
?>
Note that I've also changed your DB structure. In general, it's best to avoid putting more than one piece of data into a single field (DB normalization).

Categories