Server Side Events, HTML5, PHP & Javascript... index page not 'refreshing' - javascript

I found a really good article with a feature I want to add to a page, but have been stuck the entire day with one small error. For reference the tutorial is located here.
Everything is working, the only thing that is not happening is the fact that the index.php webpage is not refreshing on changes made to the hosted php array. Could anyone glance at my code and tell me if I have a typo or missed part of the article?
My array file - selectedSystemStateResults.php
<?php
$selectedSystemStateResults = ["cart", "dogsss", "cows", "zebra", "snake"];
My serverside PHP script file - selectedSystemState-script.php
<?php
header("Cache-Control: no-cache");
header("Content-Type: text/event-stream");
// Require the file which contains the $animals array
require_once "selectedSystemStateResults.php";
// Encode the php array in json format to include it in the response
$selectedSystemStateResults = json_encode($selectedSystemStateResults);
echo "data: $selectedSystemStateResults" . "\n\n";
flush();
echo "retry: 1000\n";
echo "event: selectedSystemStateResultsMessage\n";
My Client side web page - index.php
<?php require "selectedSystemStateResults.php"; ?>
<html>
<body>
<?php foreach ($selectedSystemStateResults as $selectedSystemStateResult) : ?>
<li><?php echo $selectedSystemStateResult; ?></li>
<?php endforeach ?>
</ul>
<script src="/selectedSystemState-script.js"></script>
</body>
</html>
My javascript file - selectedSystemState-script.js
let eventSource = new EventSource('selectedSystemState-script.php');
eventSource.addEventListener("selectedSystemStateResultsMessage", function(event) {
let data = JSON.parse(event.data);
let listElements = document.getElementsByTagName("li");
for (let i = 0; i < listElements.length; i++) {
let selectedSystemStateResults = listElements[i].textContent;
if (!data.includes(selectedSystemStateResults)) {
listElements[i].style.color = "red";
}
}
});
I have read this and re-read this for the past 8 hours and feel really stuck. Does anyone see any blaring php or javascript typos or could the tutorial be wrong?
Please pardon the typo I had in the file names on my unedited original post. The directory shows the files all named properly.

Using this tutorial Using server-sent events
I found out that the script.php file must NOT stop executing !!
or (selectedSystemState-script.php) in your case .
So I guess the the tutorial you linked is wrong in some point ?
try this
while (1) {
// Every second, send a "selectedSystemStateResultsMessage" event.
echo "event: selectedSystemStateResultsMessage\n";
require("selectedSystemStateResults.php");
$selectedSystemStateResults = json_encode($selectedSystemStateResults);
echo "data: $selectedSystemStateResults" . "\n\n";
ob_end_flush();
flush();
sleep(1);
}
this is new to me but i noticed a few things :
1- the php event script file must have header text/event-stream
2- that file must not stop executing !
3- event: is sent before data: .
Hope this help
EDIT
After a test on your script It worked when I changed
<script src="/selectedSystemState-script.js"></script>
to <script src="./selectedSystemState-script.js"></script>
it was calling selectedSystemState-script.js from root folder ! and generate 404 error
and in selectedSystemState-script.php
<?php
header("Cache-Control: no-cache");
header("Content-Type: text/event-stream");
// Require the file which contains the $animals array
require_once "selectedSystemStateResults.php";
// Encode the php array in json format to include it in the response
$selectedSystemStateResults = json_encode($selectedSystemStateResults);
// data after event
flush();
echo "retry: 1000\n";
echo "event: selectedSystemStateResultsMessage\n";
echo "data: $selectedSystemStateResults" . "\n\n";
?>
and I edited selectedSystemState-script.js a bit :
let eventSource = new EventSource('selectedSystemState-script.php');
eventSource.addEventListener("selectedSystemStateResultsMessage", function(event) {
let data = JSON.parse(event.data);
let listElements = document.getElementsByTagName("li");
for (let i = 0; i < listElements.length; i++) {
let selectedSystemStateResults = listElements[i].textContent;
if (!data.includes(selectedSystemStateResults)) {
listElements[i].style.color = "red";
} else {
listElements[i].style.color = "blue";
}
}
});

<script src="/selectedSystemState-script.js"></script>
does not match your javascript filename selectSystemState-script.js. Verify javascript errors next time by opening the developer tools console!
Another error is that you're sending the data before setting the event name. The end of selectedSystemState-script.php should be:
echo "retry: 1000\n";
echo "event: selectedSystemStateResultsMessage\n";
echo "data: $selectedSystemStateResults" . "\n\n";
flush();

Related

Issues displaying data from a PHP script on HTML 5 webpage

I am attempting to display the result of the PHP script on my webpage. To make sure that it actually works and recieves the data. Currently this isn't working. I have code in 3 seperate files that is supposed to handle this.
index.html
<div id="infoBoks">
<section>
<h1> Informasjon </h1>
<p id="parkInfo">test</p>
</section>
<section>
<h1> Innstillinger </h1>
</section>
</div>
script/javascript.js
var source = new EventSource("script/hent-status.php");
source.onmessage = function(e) {
document.getElementById('parkInfo').innerHTML += e.data + "<br>";
};
The PHP file has 3 different outputs: time, frequency and data. The data variable is a hardcoded array that is a part of a function that grabs a randomized index from the array. data[random] is then what is supposed to be returned with the script. The data is also supposed to be refreshed after a certain time, decided by the frequency variable. The PHP file is provided as a part of the project I'm currently working on. Currently I'm unsure where to proceed from this, seeing as i would expect this code to work based on the theory material I've been through.
*Note: The PHP file is also placed within the script folder.
*Note: Yes, there is a reference to the javascript file within index.html. There is also other code in the .js file that works fine with the .html file.
Edit* included hent-status.php
<?php
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
function sendMelding($id, $beskjed, $frekvens){
echo "retry: $frekvens" . PHP_EOL;
echo "id: $id" . PHP_EOL;
echo "data: $beskjed" . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
$serverTime = time();
$beskjed = hentTidspunkt($serverTime);
if (isset($_GET['t'])){
$frekvens = $_GET['t'];
}
else {
$frekvens = 5;
}
sendMelding($serverTime, $beskjed, $frekvens*1000);
function hentTidspunkt(){
$data = array(
"P1,35,50;P2,10,10;P3,25,150;P4,75,250",
"P1,38,50;P2,9,10;P3,30,150;P4,89,250",
"P1,39,50;P2,10,10;P3,35,150;P4,95,250",
"P1,34,50;P2,8,10;P3,45,150;P4,109,250",
"P1,33,50;P2,6,10;P3,55,150;P4,150,250",
"P1,30,50;P2,4,10;P3,65,150;P4,175,250",
"P1,23,50;P2,3,10;P3,65,150;P4,175,250",
"P1,43,50;P2,2,10;P3,65,150;P4,225,250",
"P1,12,50;P2,5,10;P3,50,150;P4,225,250",
"P1,15,50;P2,6,10;P3,80,150;P4,225,250",
"P1,16,50;P2,6,10;P3,100,150;P4,225,250",
"P1,25,50;P2,7,10;P3,150,150;P4,200,250",
"P1,24,50;P2,7,10;P3,149,150;P4,225,250",
"P1,18,50;P2,4,10;P3,149,150;P4,250,250",
"P1,11,50;P2,3,10;P3,115,150;P4,245,250",
"P1,45,50;P2,7,10;P3,70,150;P4,244,250",
"P1,45,50;P2,5,10;P3,60,150;P4,244,250",
"P1,45,50;P2,5,10;P3,50,150;P4,200,250",
"P1,45,50;P2,7,10;P3,40,150;P4,200,250",
"P1,50,50;P2,10,10;P3,140,150;P4,200,250"
);
$tilfeldig = rand(0,count($data)-1);
return $data[$tilfeldig];
}
?>

How to prevent echo in PHP and get what it is inside?

Referring this post how-to-prevent-echo-in-php-and-catch-what-it-is-inside i am trying to get the output values from below mentioned php file but i can see still the values are getting printed in output of my php page.Any other suggestion are also welocme to get the output content from my php file to string without getting it echoed.Thanks!
<?php include('Crypto.php')?>
<?php
$workingKey='XXXX'; //Working Key should be provided here.
$encResponse=$_POST["encResp"]; //This is the response sent by the Server
$rcvdString=decrypt($encResponse,$workingKey); //Crypto Decryption used as per the specified working key.
$order_status="";
$order_id=0;
$decryptValues=explode('&', $rcvdString);
$dataSize=sizeof($decryptValues);
echo "<center>";
for($i = 0; $i < $dataSize; $i++)
{
$information=explode('=',$decryptValues[$i]);
if($i==0) $order_id = $information[1];
if($i==1) $tracking_id = $information[1];
if($i==3) $order_status = $information[1];
}
ob_start();
echo $order_id."_";
$out1 = ob_get_contents();
echo $tracking_id."_";
$out2 = ob_get_contents();
echo $order_status;
$out3 = ob_get_contents();
ob_end_clean();
var_dump($out3);
?>
JAVASCRIPT code to get echo'ed values in HTML format
class MyJavaScriptInterface
{
#JavascriptInterface
#SuppressWarnings("unused")
public void processHTML(final String html)
{
String order_page = ""+Html.fromHtml(html);//process php output to html
String CCAvenueOrder_id = order_page.split("\\_")[0];
String CCAvenueTacking_id=order_page.split("\\_")[1];
String CCAvenueOrderStatus=order_page.split("\\_")[2];
// process the html as needed by the app
String status = null;
if(html.indexOf("Failure")!=-1){
status = "Transaction Declined!";
}else if(html.indexOf("Success")!=-1){
status = "Transaction Successful!";
}else if(html.indexOf("Aborted")!=-1){
status = " Transaction Cancelled!";
}else{
status = "Status Not Known!";
}
//Toast.makeText(getApplicationContext(), status, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),StatusActivity.class);
startActivity(intent);
}
}
Like in the comments of your question you can store the input in a variable. The use of the output buffer is not necessary, at least not in your example.
<?php
$workingKey='XXXX'; //Working Key should be provided here.
$encResponse=$_POST["encResp"]; //This is the response sent by the Server
$rcvdString=decrypt($encResponse,$workingKey); //Crypto Decryption used as per the specified working key.
$order_status="";
$order_id=0;
$decryptValues=explode('&', $rcvdString);
$dataSize=sizeof($decryptValues);
$output = "<center>";
for ($i = 0; $i < $dataSize; $i++) {
$information=explode('=',$decryptValues[$i]);
if($i==0) $order_id = $information[1];
if($i==1) $tracking_id = $information[1];
if($i==3) $order_status = $information[1];
}
$output .= $order_id."_";
$output .= $tracking_id."_";
$output .= $order_status;
echo $output; // response for ajax request as simple string
?>
If this does not work out for you please show us what is being echo'ed.
The best way to check what's going on inside running code is to use a debugger, for example xdebug. Find out how to install it and use with your IDE of choice, then place breakpoints and use watches to peek inside variables. Here's how to do it with PhpStorm.
If you cannot install a debugger, or you absolutely need to persist the values, learn the concept of logs. There is a PHP-FIG standard for logging (PSR-3) and at least one tool that implements it - for example, Monolog.

Array of Javascript in PHP

I was trying to get datas from the database and put them into the array in Javascript but Javascript is not working in PHP command area.
Here is the whole PHP codes;
<?php
mysql_connect("mysql.metropolia.fi","localhost","") or die("ERROR!!");
mysql_select_db("localhost") or die("COULDN'T FIND IT!!") or die("COULDN'T FIND DB");
$sql = mysql_query("SELECT * FROM METEKSAN_HABER_CUBUGU");
$haber = 'haber';
$list = array();
$i=0;
while($rows = mysql_fetch_assoc($sql)){
$list[] = $rows[$haber];
$i++;
}
echo $i;
echo '<script type="text/javascript">
var yazi=new Array();';
echo $i;
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']="'.$list[$k].'';
}
echo '</script>';
?>
But when it comes to;
echo '<script type="text/javascript">
var yazi=new Array();';
this command line, the problem begins. Though I write 'echo $i;' after that command, I get nothing on the screen but I get the result if I write before that command. So, it means that everything works well before that command. What you think about the problem ? Why can't I starting the Javascript command ? Am I writing something wrong ?
Please give me a hand.
Thanks.
UPDATE;
I opened the web source and yeah it exactly seems there is a problem. So, I think it's better to ask that how can I write
<script type="text/javascript">
/*Example message arrays for the two demo scrollers*/
var yazi=new Array()
yazi[0]='METEKSAN Savunma, Yeni Dönemin Örnek Oyuncusu Olmaya Hazır'
yazi[1]='METEKSAN Savunma Bloomberg TVde'
</script>
this Javascript code in PHP ??
You can see my output at http://users.metropolia.fi/~buraku/Meteksan/index.php
try something like this
while($rows = mysql_fetch_assoc($sql)){
$list[] = ''.$rows[$haber].'';
}
$js_array = json_encode($list);
echo "<script>var yazi = ". $js_array . ";</script>";
It seems you are executing it currently in your browser? Then you should find your second output when opening page source, because your browser tries to executes the output as JS code. If you execute it on cli, everything should work as expected.
EDIT based on your comment:
Bullshit i wrote before, obviously. Viewing line 122 of your current html shows me a problem with your quotation marks. try the following:
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']=\''.$list[$k].'\';';
}
In the end you should try to avoid using this kind of js rendering at all. The json_encode proposal of jeremy is the correct way to go.
You may have much more compact code:
....
$list = array()
while($rows = mysql_fetch_assoc($sql)) {
$list[] = $rows[$haber];
}
echo '<script type="text/javascript">' . "\n";
echo 'var yazi=';
echo json_encode($list,JSON_HEX_APOS | JSON_HEX_QUOT);
echo ";\n";
echo '</script>' . "\n";
What is this doing:
There's no need to count the added elements in $i, count($array) will give you the cutrrent number.. But it's not needed anyway.
Put some newlines behind the echo, better readable source
json_encode will format an JSON array from your php array, which can be directly used as source code.

How to use javascript in PHP? The script tag is not recognized

I don't know why but the script tag is not working, the SELECT query is working but i am not getting the prompt from the javascript.
it is not redirecting anywhere only a blank screen is seen
$qry1="SELECT area, aadhar FROM user where username='$user'";
$result1 = $connector->query($qry1);
if($result1){
$row1=mysql_fetch_array($result1);
$userarea= $row1['area'];
$useraadhar=$row1['aadhar'];
}?>
<body>
<script type="text/javascript">
var inputarea=<?php echo $coursename; ?>;
var userarea=<?php echo $userarea; ?>;
var useraadhar=<?php echo $useraadhar;?>'
if(inputarea==userarea){
<?php/
//date
$today = date("Y-m-d");
//Create INSERT query
$qry = "INSERT INTO complain (user,category,regno,course,lecturer,room,details,address,datein) VALUES ('$userid','$category','$reg','$coursename','$lectname','$roomno','$details','$address','$today')";
//$result = #mysql_query($qry);
$result = $connector->query($qry);
//Check whether difjslk the query was successful or not
if($result) {
$errmsg_arr[] = 'Complain succesfully added, please wait for your response';
$errflag = true;
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: _new_complains.php");
exit();
}
header("location: _new_complains.php");
exit();
}else {
die("Query failed, couldn't add the new record");
header("location: _new_complains.php");
exit();
}
?>
}
You are sending data (for example body tag) before header(), therefore PHP creates an error. You just don't see it. Header needs to come before anything is sent to the browser (even a space).
You have multiple JS syntax errors:
var inputarea=<?php echo $coursename; ?>;
var userarea=<?php echo $userarea; ?>;
var useraadhar=<?php echo $useraadhar;?>'
Never EVER dump out raw text from PHP into a Javascript context. You're generating code that looks like
var inputarea=foo;
var userarea=bar;
var useradhar=baz';
The data will be seen as undefined variables, and you've got a stray ' in there. All of these errors will KILL the entire <script> block.
Always use json_encode() to dump from PHP->JS:
var inputarea = <?php echo json_encode($coursename); ?>;
This will GUARANTEE that you're producing correct Javascript code. The above line would produce
var inputarea = 'foo';
and be perfectly valid and executable code.

Re-execute a PHP script in a JavaScript function

I wrote a code to re-read a content of a file (on the server) every time the file is modified. The scenario is like this:
- The webpage is loaded
- If the file (on the server) is newer than the starting time of the page (the time when the webpage was started), the content of the file is read
- If the file is modified later, the content must be read again by PHP script
I tried this using EventSource. Here is the code for the browser:
<html>
<head>
<?php
$startTime = time();
$flag = 0;
?>
<script type="text/javascript" language="javascript">
lastFileTime = <?php echo $startTime; ?>;
var fileTime;
if(typeof(EventSource) !== "undefined") {
var source=new EventSource("getFileTime.php");
source.onmessage = function(event) {
fileTime = parseInt(event.data);
if (fileTime > lastFileTime) {
readFile();
lastFileTime = fileTime;
}
};
}
else {
alert("Sorry, your browser does not support server-sent events.");
}
function readFile() {
<?php
$fid = fopen("file.bin", "rb");
... // Read the content of the file
$flag = $flag + 1;
?>
... // Transfer the content of the file to JavaScript variables
flag = <?php echo $flag; ?>;
}
</script>
</head>
<body>
...
</body>
</html>
And here is the server-side code (getFileTime.php):
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$filetime = filemtime("file.bin");
echo "data: {$filetime}\n\n";
flush();
?>
When I start the webpage and created file.bin afterwards, readFile() is called for the first time (I checked the value flag = 1. But then, if I modified file.bin again, obviously readFile() is not called. I checked the content of the file; it's still from the previous file, and also flag is still 1. It seems that a PHP script in a JavaScript function can only be called once. How to re-execute the PHP script in a JavaScript function?
Your PHP script needs to remain active, sending new events to the client when something changes:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$lastFiletime = null;
while (true) {
$filetime = filemtime("file.bin");
if ($filetime != $lastFiletime) {
echo "data: {$filetime}\n\n";
$lastFiletime = $filetime;
flush();
}
}

Categories