I am using the following code to send mysql database content into a javascript array. This works fine when I start the page, but when the database gets a new entry, the new entries are not added to the array when I rerun this bit of code - unless I reload the entire page.
<p><button onclick="save_image()">Send image</button></p>
<script type="text/javascript">
function save_image(){
var userName =
<?php
$conn = new mysqli(.........."); //connect to database
$d = mysqli_query($conn, "SELECT name FROM canvas_data" );
$usernames = array();
while( $r = mysqli_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>;
console.log(userName)
}
</script>
I realize there are other pages about this topic, but I didn't know how to apply them to my case. If you have some ideas. Thanks.
If you want to get information from the database without reloading the page, you'd need to do an Ajax request to retrieve the information.
Something like this would work:
PHP - ajaxendpoint.php
<?php
$d = mysqli_query($conn, "SELECT name FROM canvas_data" );
$usernames = array();
while( $r = mysqli_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>
JavaScript
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText); //log the response from the database
//if the PHP is returning a JSON object, you can parse that:
var myArray = JSON.parse(xhttp.responseText);
}
}
xhttp.open("GET", "ajaxendpoint.php", true);
xhttp.send();
}
HTML - index.html
<button onclick="getData()">
Load Data via Ajax
</button>
Here is another example Ajax request in this JS Fiddle: https://jsfiddle.net/igor_9000/77xynchz/1/
Related
I have been spending lots of time trying to figure out the issue. Nothing is working though. It continues to send the PHP file as text.
This is my javascript file with the ajax request.
var ajax = new XMLHttpRequest();
var method = "GET";
var url = "http://localhost:8000/createTable.PHP";
//send ajax request
ajax.open(method, url, true);
ajax.send();
//retrieve table data
ajax.onreadystatechange = function () {
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
//convert data to array
alert(this.responseText);
var data = JSON.parse(this.responseText);
}
and this is my php file which is alerted as is on my website.
//connect to MYSQL
require_once('../connectSQL.php');
//query
$result = mysqli_query("SELECT * FROM fitness");
//
$to_encode = array();
while ($row = mysqul_fetch_assoc($result)){
$to_encode[] = row;
}
echo json_encode($to_encode);
mysqli_close($dbc);
//fclose($myfile);
My php file work fine when I'm sending json from javascript file to php for storing in database. However, now that I'm retrieving data from database, seems like the PHP file is not being read as PHP.
I have tried changing all sorts of things in httpd.conf. Using apache 7 and mac osx.
You must insert PHP tags, so the server understands this code as PHP
in this case it would look like this:
<?php
//connect to MYSQL
require_once('../connectSQL.php');
//query
$result = mysqli_query("SELECT * FROM fitness");
//
$to_encode = array();
while ($row = mysqul_fetch_assoc($result)){
$to_encode[] = row;
}
echo json_encode($to_encode);
mysqli_close($dbc);
//fclose($myfile);
?>
I am fetching data from a psql table and passing it to javascript as json array for display as a time series chart. The data passed needs to be in the from of an array.
As the data in the table is updated periodically, I need to constantly fetch the data from psql e.g. every 15 minutes and pass updated array to javascript.
I search but so far I couldn't any solution. My question is how can I fetch data from psql periodically.
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<script>
var Device_Data;
var time, batt;
var timeArray = [];
var battArray = [];
var N = 12;
for (i = 0; i < N; i++) {
timeArray.push(0);
battArray.push(0); }
function dspChrt(Device_Data) {
console.log(Device_Data[0].date_time);
console.log(Device_Data[1].battery_voltage_mv);
time = Device_Data[0].date_time;
batt = Device_Data[1].battery_voltage_mv;
timeArray.shift();
timeArray.push(time);
battArray.shift();
battArray.push(batt);
</script>
</head>
<body>
<?php
require("Connection.php");
$stmt = $conn->prepare("Select date_time, battery_voltage_mv FROM measuring_device_statuses order by date_time desc limit 12");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = $stmt->fetchAll();
/*
echo "<pre>".print_r($WData, true)."</pre>";
die();
*/
?>
<script>
var WData = <?php print_r(json_encode($WData));?>;
//console.log(WData);
dspChrt(WData);
</script>
</body>
</html>
Keep you data fetch php script in some file "fetch.php" and through javascript set interval function call it periodically for example this code prints alert every 3 secs.
setInterval(function(){ alert("Hello"); }, 3000);
You can use AJAX for this purpose.
HTML
<div id="myDiv"></div>
JavaScript
<script>
window.onload = function(){
loadDoc();
SetInverval(loadDoc, (10000 * 60 * 15)); // Perform function every fifteen minutes
}
function loadDoc() {
var div = document.getElementById("myDiv"); // Get Div
div.innerHTML = ""; // Set to nothing
var xhttp = new XMLHttpRequest(); // Create new XML object
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) { // If successful
div.innerHTML = this.responseText; // Display result
}
};
xhttp.open("GET", "loadDoc.php", true);
xhttp.send();
}
This should be in your PHP file, named loadDoc.php or whatever you choose to replace it to.
<?php
require("Connection.php");
$stmt = $conn->prepare("SELECT date_time, battery_voltage_mv FROM measuring_device_statuses ORDER BY date_time DESC LIMIT 12");
$stmt->execute();
//$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = $stmt->fetchAll();
$stmt->close();
echo "<pre>".print_r($WData, true)."</pre>";
die();
?>
I just wanted to retrieve some PHP/Mysql stuff at the beginning of my app (authentication and x and y data) from the users which I later plan to emit to the app.js (one time at the beginning and once the user disconnects update x - y values).
So basically I have set up Nodes.js and understood that some stuff is not possible like before (e.g with plain php)
Where I already have a problem is the AJAX php request in the index.html of my nodes Server
Schema:
app.js: pull Data from the /Client/index.html (I think need to do it via sockets)
index.html: get or post data via Ajax to a php file and get the values of the database back to the index.html(JavaScript)
then send that data via sockets to the app.js
php: select mysql database
retrieve values from mysql
parse them via Json and make them available in the index.html file Nodes.js (Client)
Maybe somebody of you have a solution
Nodes.js /Client/index.html:
function checkuser(username, password) {
var myObj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
myObj = xhttp.responseText;
var i = 0;
while (i <= myObj.length) {
//console.log("ASQL found and Auth Username:"+ myObj[i].username) ;
console.log(myObj.username);
i++;
}
}
};
xhttp.open("GET", "/client/is_user.php?username333=" + username + "&password333=" + password, true);
xhttp.send();
}
is_user.php:
<?php
require('config_sql.php');
$email = stripslashes($_GET['username333']);
$email = mysqli_real_escape_string($con,$email);
$password369 = stripslashes($_GET['password333']);
$password369 = mysqli_real_escape_string($con,$password369);
$query = "SELECT * FROM `users` WHERE email='$email'
and password='".md5($password369)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$response = array();
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row;
}
$jsonData = json_encode($response);
echo $jsonData;
mysqli_close($con);
?>
atm is not retrieving the username form the created json on the php side.
If I console.log(myObj); it's showing the me complete php.file data as plain text if I want to retrieve the username from MySql its saying undefined.
Is the php Interpreter actually working when I post/get via Ajax in a Node.js environment?
Normally when I was programming with pure php all the request worked well.
Thank you in advance.
Check you code for recieving result from query:
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row;
}
$jsonData = json_encode($response);
Should be so:
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row_user;
}
$jsonData = json_encode($response);
I'm trying to create a chatbox using AJAX but for some reason my xhttp.responseText is empty. In firebug I can see that a GET request is being sent and it even responds with the correct text, but this text just doesn't get put in the responseText for some reason.
Here is my index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chatroom</title>
<script>
function setup() {
ajaxRequest( 'GET', 'loadmessages.php', updateChat);
setInterval(function () {
ajaxRequest( 'GET', 'loadmessages.php', updateChat);
}, 1000);
}
function updateChat(xhttp) {
document.getElementById( 'chat' ).innerHTML = xhttp.responseText;
}
function ajaxRequest( method, file, cfunc ) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if(xhttp.readyState == 2 && xhttp.status == 200) {
cfunc(xhttp);
}
}
xhttp.open( method, file, true);
xhttp.send();
}
</script>
</head>
<body onload="setup();">
<div id="chat">
</div>
</body>
</html>
Here is loadmessages.php:
<?php
include( 'connect.php' );
$query = "SELECT * FROM messages ORDER BY id DESC";
$result = mysqli_query($conn, $query);
if( mysqli_num_rows($result) > 0 ) {
$output = "";
while( $row = mysqli_fetch_assoc($result) ) {
$id = $row['id'];
$name = $row['name'];
$content = $row['content'];
$time = $row['time'];
$output .= "[sent by $name on $time] $content <hr/>";
}
echo $output;
} else {
echo "No messages yet, be the first to send one!";
}
mysqli_close($conn);
?>
And the connect.php:
<?php
$conn = mysqli_connect( 'localhost', 'root', '', 'chatroom' ) or die( 'Couldn\'t connect to database!' );
?>
Since there's nothing in the database yet, it just echoes "No messages yet, be the first to send one!". I can see this response if I open firebug, but this text is not in the responseText variable.
You should change the if clause for readyState like below:
xhttp.onreadystatechange = function () {
if(xhttp.readyState == 4) {
cfunc(xhttp);
}
}
since this callback is triggered everytime the readyState changes and you are testing for the value 2 which is sent, at this point there is no response available in xhttp.responseText
See here What do the different readystates in XMLHttpRequest mean, and how can I use them?
In slightly more detail here Why XmlHttpRequest readyState = 2 on 200 HTTP response code
the difference between readyState==2 and readyState==4
I highly recommend using jQuery for AJAX, because it is far more simple and intuitive. Here is link for more info: http://www.w3schools.com/jquery/jquery_ref_ajax.asp
So following my last question I want to use the value that is submitted in the input tag to get the matching id in my database. I have created two files for it but I can't figure out how to link them. Also note I made a database with a few values(id, firstname, etc.) and when the user fills in 1 I want it to display id 1 & the firstname.
This code is from the last question & I've added xmlhttp:
Input code
Choose a number between 1 and 5
Your info shall be shown here
Click me!
var myButton = document.getElementById('btn');
myButton.onclick = function(){
alert(document.getElementById('myid').value);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if( xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var dbText = xmlhttp.responseText;
document.getElementById('dbinfo').innerHTML = dbText;
}
}
xmlhttp.open("POST", "LinkToDataFile", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
That is what the user sees and the number is displayed correctly however I now need to link it to my file data.php which I have tried but it cannot get the value.
Data Code
<?php
require_once('input_code');
//Get the data from the database and echo them here
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "db_name";
try
{
$connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("SELECT `id`, `firstname`, FROM `db_name` WHERE `id` = :myid"); //Here it needs to grab the value but it does not work.
$statement->bindParam(':id', $id);
$id = $_POST['id'];
$statement->execute();
$result = $statement->setFetchMode(PDO::FETCH_ASSOC);
$data = "";
foreach($statement->fetchAll() as $key => $value)
{
$data .= $value['id']." | ".$value['firstname'];
}
}
catch(PDOException $e)
{
echo "The following error occurred : ".$e->getMessage();
}
echo $data;
?>
So what am I doing wrong? am I missing something obvious like the $id again or is it a series of errors, the only thing it does now is giving me an alert with the number.
By adding a line and moving $id before $statement it is all fix thanks to Dante Javier
Input code
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //Under this add the following lines:
var id = document.getElementById('myid').value;
xmlhttp.send("id="+id);
Data Code
$id = $_POST['id']; //Move this above the $statement = $connection->prepare.