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];
}
?>
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.
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.
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.
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();
}
}