accessing php variables using javascript - javascript

I've done created a webpage, set up appache2 on ubuntu server so I can view this page over the internet. I've installed php5 and MySQL and would like to access information in the database on the webpage that I've created.
Right now, I've got a file test.php that accesses the database and puts some of the information into variables. I've scripted using javascript something that will change the webpage content at the click of a button.
Now, the webpage crashes whenever the button is pushed as it says the variables are undefined or null references. Fair enough, but my question is how does one access variables on a .php file through the webpage? Can a browser use information in the .php file if I script it into the page?
I was told that the php file would be parsed automatically. I'm guessing that server side this page is being accessed but I can use it through web browser.
Edit:
//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];
?>
Ok so I changed the php file to this, so now all it is doing is defining variables. I installed a couple of MySQL mods and no problems now.
next issue is how do I get use php variables in javascript
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;?>;
}
}
}
So onload this ajax function should run and change itemNameLink1 to the php variable $n1, only it doesn't and I just get an empty string. Everything should be set up right but using the php variable seems impossible. would it be any easier with the jquery get command, I'm guessing that unless I sort this out I'm gonna struggle.
I'm also assuming a few things, I've checked error logs and the php file is active assuming I've connected right it should be accessing the database. I'm very new so I do not know how to test this.
I'm also assuming that when php file is in the server webpage file directory. that it is automatically working. again very new to setting up a server so using ubuntu server and being familiar with all the commands that I need to use or how apache2 operates is difficult for me.

PHP Is executed on the server, your client receives the result as a plain text/html document.
Your browser runs the javascript when it received the plain document, so you can't access PHP vars directly with javascript.
But you could set javascript variables when the page is generated on the server like this
<?php $myPhpVar = 'Hello World'; ?>
<script>
//This line would result in var test = "Hello World"; when send to client
var test = "<?=$myPhpVar?>";
alert(test);
</script>
Furthermore you can execute requests to your server with javascript (so you can read the result from test2.php as example, and use that somewhere on your page). http://en.wikipedia.org/wiki/Ajax_(programming)
Pure javascript: http://en.wikipedia.org/wiki/XMLHttpRequest
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE){
alert(this.readyState);
}
};
var action = 'doSomethingOnServer';
request.open('GET', 'test2.php?action=' + action, true);
request.send(null);
Jquery: http://api.jquery.com/jquery.ajax/
<script>
var action = 'doSomethingOnServer';
$.ajax({
url: "test2.php?action=" + action,
}).done(function(result) {
alert(result);
});
<script>
For testing if your php works on your server create a file info.php (or something). and add this to the file
<?php phpinfo(); ?>
If you access that page you should get a page with a lot of information about your php configuration.
I'm not sure how you did install your php, but on a development machine you can change a few things in your php.ini that makes life easier
display_startup_errors = 1
display_errors = 1
error_reporting = E_ALL
See http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting when you change your php.ini don't forget to restart your apache
JSON Example:
data.php
<?php
$db_result = array(array('name' => 'record1'), array('name' => 'record2'));
echo json_encode($db_result);
?>
index.php
<script>
$.ajax({url: 'data.php', dataType: 'json'}).done(function(result) {
//result = an object from your database (in this case an array with objects with the property name)
alert(result);
alert(result[0].name);
}
</script>

Related

Raspberry Pi Server php does not work from outside local network

I have been making a small page on my server to display some photo albums. This is on an nginx server on a raspberry pi 4. When I try to access the page from my laptop or phone when they are on wifi, everything loads correctly. However, when I use my phone with LTE, for example, the php requests do not work. I checked with my laptop using my wireless hotspot and I had the same issue. I never get the "200" code that my browser is waiting for. I do not get an error either. It is as though the http request disappears. I have other pages on this same server where the php is working correctly, one of which is almost the exact same as this code. The php I am trying to use is one which returns file and album names as a long string. Expected output would be:
Siblings|Wyoming|Utah|Skiing|
This all works when accessed from my local network. In the past I have used much more elaborate php files to access security camera footage and also send shell scripts to turn a relay on and off. These worked from anywhere in the world, not just my network. I know very little about this stuff, so I'm hoping I am just missing something obvious that an expert can recognize immediately. :) I will include my code below.
getfiles.php
<?php
function clean_scandir($dir){
return array_values(array_diff(scandir($dir),array('.','..')));
}
$directory = $_GET['dir'];
$files = clean_scandir("/var/www/html/" . $directory);
foreach($files as $file){
$fileStr .= $file . "|";
}
echo $fileStr;
?>
And the javascript that is trying to use this php:
function getAlbums(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
console.log("return packet = " + this.response);
var albumArray = this.response.split("|");
albumArray.pop(); //remove empty last element
for (var i = 0; i < albumArray.length; i++){
console.log("album " + i + " = " + albumArray[i]);
}
getThumbnail(albumArray);
setTimeout(() => {
populateAlbums(albumArray); //waits 1 sec for thumbnail requests to finish before loading thumbnails
}, 1000);
}
}
var urlString = "getfiles.php?dir=" + "photos/";
xmlhttp.open("GET", urlString, true);
xmlhttp.send();
}
The code never arrives at the console.logs that are within the big 'if' statement, I am assuming because the status never reaches 200. I do not get any other number like a 500 code. It just remains blank.
I have tried slowly modifying the php code. If the file is simply:
echo "php successful";
then it works. But for some reason the full code is causing issues. Sometimes the issues do not act the same each time either.

PHP not detecting POST JSON data from JavaScript request

I am in need of a little help with a small bit of my code that is essential to my application. I am making a small clicker game, and I want users to be able to save and load data via PHP to my server. I do not want to use Local Storage to make it harder for anyone to edit their economy and "cheat". When the user clicks on a save button I have, it fires my vue method which initializes the saving. I have had no problem getting the data into a JSON format, however I cannot get PHP to read this data via POST. I have checked for network headers, and it shows that stuff is being sent, it seems that PHP just isn't catching it. I'll include the code for the JS part and PHP part below. The PHP is only set to echo if the array_key_exists right now, as after getting this sorted out I will easily be able to handle the rest. Any help would be greatly appreciated!
I have tried to follow this, which has not worked so far Send JSON data from Javascript to PHP?
JS
saloOut: function() {
var saveData = {
saveMoney: this.money,
saveCrystals: this.crystals,
};
saveData = "saveData=" + (JSON.stringify(saveData));
var sendData = new XMLHttpRequest();
sendData.open("POST", "salo.php", true);
sendData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendData.send(saveData);
console.log(saveData);
}
PHP
<?php
if (array_key_exists("saveData", $_POST)) {
echo "<p>SALO Ready!</p>";
}
?>
Decode the JSON string at the PHP end before accessing values, like this:
<?php
if(isset($_POST['saveData'])){
$result = json_decode($_POST['saveData'], true);
// use $result['saveMoney'] and $result['saveCrystals'] accordingly
}
?>
Update# 1:
As OP commented below, I expect that it will print "SALO Ready" but it is instead doing nothing
That's because you are not using responseText property of XMLHttpRequest object to see the text received from the server. Use below snippet to see the response text.
saloOut: function() {
var saveData = {
saveMoney: this.money,
saveCrystals: this.crystals,
};
saveData = "saveData=" + (JSON.stringify(saveData));
var sendData = new XMLHttpRequest();
sendData.open("POST", "salo.php", true);
sendData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendData.send(saveData);
sendData.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
}
Reference: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText

Pushing data from one client to another using Php

I am making my college project on Air Quality Monitoring System, in that data (say some integer value) has to be taken from sensing unit to a webpage.
What I want
Is that the script called upon by this url http://localhost/AQProject/recordupdate.php?val=2 updates a web page displaying the content. Now I know I can save that data in database and run ajax based query every two seconds to check for update, but I want that update to be pushed by server.
What have I done:
I have tried Server sent events. Here's what i tried
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
if($_SERVER["REQUEST_METHOD"]=="GET")
{
if(empty($_GET["val"])) die ("Empty Value from source");
else
{
$v = $_GET['val'];
echo "data: The Pollution stub value is {$v}".PHP_EOL;
ob_flush();
flush();
}
}?>
and html has script
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("recordupdate.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data +
"<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
Now, I have figured out this much that (correct me If i am wrong) it won't work because when another client (sensing unit) calls for recordupdate.php its a different instance of that script than that called by webpage client.
Is there any possible way of doing this using server sent events? Or I absolutely need to dig into websockets, node.js etc. Thanks in advance
What you want to do is not quite as easy as you hoped, but this is still a job for which SSE is suited. You don't need to use sockets, and don't need to use ajax polling.
But you do need some database store, on the server, that can be shared by PHP scripts. As installing a LAMP stack is so easy, I'd recommend using MySQL, even though it might be overkill for what you need. But your database could be as simple as a text file.
(To keep the below samples as small as possible, I've assumed your DB will be /tmp/val.txt, and I've not done any file locking, or checking for bad data. Just be aware that you need to do some work before putting this in production in an untrusted environment. I'd recommend pre-creating /tmp/val.txt to avoid any noise about files not existing.)
Your recordupdate.php has the job to record the value it is given:
<?php
if($_SERVER["REQUEST_METHOD"]=="GET")
{
if(empty($_GET["val"])) die ("Empty Value from source");
else file_put_contents("/tmp/val.txt", $_GET['val']);
}
You then have sse.php, which web clients connect to:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$prev = '';
while(1){
$v = file_get_contents("/tmp/val.txt");
if($v != $prev){
echo "data: The Pollution stub value is {$v}\n\n";
$prev = $v;
}
usleep(100000); //0.1s
}
This script is checking the text file for changes 10 times a second. As soon as it spots one it sends it to the client. (Mean latency is 0.05s plus network overhead.) Sleep for less time if you need lower latency.
The only change to your front-end HTML is to call "sse.php" instead:
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data +
"<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
HTTP is one way protocol. Request from client to server only. Yes, absolutely need to dig into websockets, node.js etc.

EXTJS ERROR in api.php inclusion file in script tag

i'm using sencha Extjs 6.0.2 in the forntend and mongodb in the backend. But, whenever i try to add api.php file in index.html file using script tag, it throws some exception. In index.html i add the following code for api.php file inclusion.
<script src="php/api.php" type="text/javascript" ></script>
the Error is
Uncaught SyntaxError: Unexpected token < api.php?_dc=1468481913442:1
the problem that i found during debugging is that api.php file is called as html type. As far as i know php file should call as a php type, but it doesn't. some times when i resend the file respone using firebug, it type turned into xml. How can i get rid of this problem?
And the error i found after inspecting is below:
Here is my api.php code
<?php
require('config.php');
//header('Content-Type: text/javascript');
header("content-type: application/x-javascript");
$API = get_extdirect_api('api');
// convert API config to Ext Direct spec
$actions = array();
foreach($API as $aname=>&$a){
$methods = array();
foreach($a['methods'] as $mname=>&$m){
if (isset($m['len'])) {
$md = array(
'name'=>$mname,
'len'=>$m['len']
);
} else {
$md = array(
'name'=>$mname,
'params'=>$m['params']
);
}
if(isset($m['formHandler']) && $m['formHandler']){
$md['formHandler'] = true;
}
if (isset($m['metadata'])) {
$md['metadata'] = $m['metadata'];
}
$methods[] = $md;
}
$actions[$aname] = $methods;
}
$cfg = array(
'url'=>'php/router.php',
'type'=>'remoting',
'actions'=>$actions
);
echo 'var Ext = Ext || {}; Ext.REMOTING_API = ';
echo json_encode($cfg);
echo ';';
// document.getElementById("demo").innerHTML = "Hello JavaScript";
?>
i try to send the api.php file type as JS file.
Thanks in advance
I am too new to write comments so I'll just write here I'm not sure if it is helpful but: What are you using to process the php file?
I had a similar problem while using the web server that the sencha cmd provide. This is just a basic HTTP webserver and doesn't support php so you get back the php code instead of the javascript that the php code is supposed to produce.

call PHP function inside JS [duplicate]

Is there a way I can run a php function through a JS function?
something like this:
<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php
query("hello"); ?>";
}
</script>
<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;"
onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
I basically want to run the php function query("hello"), when I click on the href called "Test" which would call the php function.
This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.
After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.
You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .
Plain Javascript
In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.
The javascript
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
The HTML
test
<div id="output">waiting for action</div>
The PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
Try it out: http://jsfiddle.net/GRMule/m8CTk/
With a javascript library (jQuery et al)
Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.
Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:
// handles the click event, sends the query
function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
Try it out: http://jsfiddle.net/GRMule/WQXXT/
Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.
If this is all you need to do, write the plain javascript once and you're done.
Documentation
AJAX on MDN - https://developer.mozilla.org/en/ajax
XMLHttpRequest on MDN - https://developer.mozilla.org/en/XMLHttpRequest
XMLHttpRequest on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
jQuery - http://jquery.com/download/
jQuery.ajax - http://api.jquery.com/jQuery.ajax/
PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.
The only way to execute PHP from JS is AJAX.
You can send data to server (for eg, GET /ajax.php?do=someFunction)
then in ajax.php you write:
function someFunction() {
echo 'Answer';
}
if ($_GET['do'] === "someFunction") {
someFunction();
}
and then, catch the answer with JS (i'm using jQuery for making AJAX requests)
Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.
I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php
Simple example usage:
// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
I have a way to make a Javascript call to a PHP function written on the page (client-side script). The PHP part 'to be executed' only occurs on the server-side on load or refreshing'. You avoid 'some' server-side resources. So, manipulating the DOM:
<?PHP
echo "You have executed the PHP function 'after loading o refreshing the page<br>";
echo "<i><br>The server programmatically, after accessing the command line resources on the server-side, copied the 'Old Content' from the 'text.txt' file and then changed 'Old Content' to 'New Content'. Finally sent the data to the browser.<br><br>But If you execute the PHP function n times your page always displays 'Old Content' n times, even though the file content is always 'New Content', which is demonstrated (proof 1) by running the 'cat texto.txt' command in your shell. Displaying this text on the client side proves (proof 2) that the browser executed the PHP function 'overflying' the PHP server-side instructions, and this is because the browser engine has restricted, unobtrusively, the execution of scripts on the client-side command line.<br><br>So, the server responds only by loading or refreshing the page, and after an Ajax call function or a PHP call via an HTML form. The rest happens on the client-side, presumably through some form of 'RAM-caching</i>'.<br><br>";
function myPhp(){
echo"The page says: Hello world!<br>";
echo "The page says that the Server '<b>said</b>': <br>1. ";
echo exec('echo $(cat texto.txt);echo "Hello world! (New content)" > texto.txt');echo "<br>";
echo "2. I have changed 'Old content' to '";
echo exec('echo $(cat texto.txt)');echo ".<br><br>";
echo "Proofs 1 and 2 say that if you want to make a new request to the server, you can do: 1. reload the page, 2. refresh the page, 3. make a call through an HTML form and PHP code, or 4. do a call through Ajax.<br><br>";
}
?>
<div id="mainx"></div>
<script>
function callPhp(){
var tagDiv1 = document.createElement("div");
tagDiv1.id = 'contentx';
tagDiv1.innerHTML = "<?php myPhp(); ?>";
document.getElementById("mainx").appendChild(tagDiv1);
}
</script>
<input type="button" value="CallPHP" onclick="callPhp()">
Note: The texto.txt file has the content 'Hello world! (Old content).
The 'fact' is that whenever I click the 'CallPhp' button I get the message 'Hello world!' printed on my page. Therefore, a server-side script is not always required to execute a PHP function via Javascript.
But the execution of the bash commands only happens while the page is loading or refreshing, never because of that kind of Javascript apparent-call raised before. Once the page is loaded, the execution of bash scripts requires a true-call (PHP, Ajax) to a server-side PHP resource.
So, If you don't want the user to know what commands are running on the server:
You 'should' use the execution of the commands indirectly through a PHP script on the server-side (PHP-form, or Ajax on the client-side).
Otherwise:
If the output of commands on the server-side is not delayed:
You 'can' use the execution of the commands directly from the page (less 'cognitive' resources—less PHP and more Bash—and less code, less time, usually easier, and more comfortable if you know the bash language).
Otherwise:
You 'must' use Ajax.

Categories