I have this file:
<html>
</html>
<script>
setInterval(function () {
<?php clearstatcache(); ?>
var ss = "<?php echo filesize('log.html'); ?>";
console.log(ss);
},100);
</script>
But if I empty out the file log.html the browser still outputs the old filesize. Am I doing something wrong here? If so how can I fix it?
Javascript you are running keeps outputting the same data that has been sent when the page loaded. Thus it never change, as it is not reading from server.
You would need to use ajax to re-read data from server whenever needed to update.
Related
I have a php file containing the following line;
$num= "<script type='text/javascript' src='hn_includes/common.js'>boo();</script>";
and of course have a javascript file common.js which contains a function boo()
This is never called...
In an attempt to debug, I've placed a console.log("common.js loaded"); at the top of the common.js file and this tells me that it is indeed being loaded but the call to function boo() never seems to happen.
Additionally, if I simply change my line of code above to;
$num= "<script>boo();</script>";
and add boo() to top of the php file as below;
<script>
console.log ("I'm here");
function boo()
{
console.log("boo");
}
</script>
I get both the "I'm here" and also the "boo".
Any suggestions on where I'm going wrong would be greatly appreciated...
You are only declaring variable in the PHP file. To make it valid accessible in page you need to echo it. like
$num= "<script type='text/javascript' src='hn_includes/common.js'>boo();</script>";
echo html_entity_decode($num);
I am trying to use the solution called in here:
How to keep session alive without reloading page?
Unfortunately I can't get it to work, I have very limited experience with Javascript and jQuery.
This is my index.php
<?php
session_start();
echo session_id();
$_SESSION['id'] = session_id(); //just so there is a variable within the session
?>
EDIT: added jquery library after comment/answer
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
setInterval(function(){
$.post('refresh_session.php');
}, 60000);
</script>
And this is the refresh_session.php where I write to a file, so I can test if the file is actually being called.
<?php
session_start();
if (isset($_SESSION['id'])){
$_SESSION['id'] = $_SESSION['id']; // or if you have any algo.
}
$date = new DateTime();
$fp = fopen('data.txt', 'a');
fwrite($fp, $date->format('Y-m-d H:i:s') . " " . session_id() ."\n");
fclose($fp);
?>
If I call refresh_session.php manually, I see the date showing up in data.txt.
If I open up index.php and wait for the data.txt file to change, nothing happens.
What am I missing here?
I don't know why, but after copy-paste your javascript code – I've got strange characters in Code Snipped. It can be charset problem. Code looks good, but bracket only looks like bracket. It's not bracket. What it is? I don't know, but look at that what I've got in Code Snipped after pasting your code:
Code will execute if you write it using good charset. Take that working code:
setInterval(function(){
$.post('refresh_session.php');
alert("dsa");
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
By the way – alert is of course only test, you can delete this.
So, the answer is – check your charset.
I'm trying to use setInterval() to reload an image from a given path. I have some similar code to reload a log file which is working fine:
var auto_refresh = setInterval(
function auto_refresh_log()
{
$('#log_output').load('refresh_log.php').fadeIn("slow");
}, 1000);
refresh_log.php:
<?php $file = "/var/www/html/mainLOG";
$contents = file($file);
$string = implode( $contents);
echo $string; ?>
Now, I want to do something similar only with 2 changes:
Instead of using a fixed path like in refresh_log.php, I want to pass the path from the JS function to the PHP file. How can I do that?
Instead of returning a string, I want to return an image, which is then used in my html document. How can I do that?
To be exact on what I want to do: I have an index.php on which a user can select a file path. After setting some further parameters, some calculations start in the background. The results are saved as TIFF-files which cannot be read by the browser. So I want to use a PHP script with imagemagick to convert them (which is working fine) and pass them back to the JS. Then, the image should be displayed on my HTML <img id="image_id" ... > and refreshed every couple of seconds just like the log file.
Thanks!
One way would be to change the src attribute of the img element.
The browser will download the resource when you change the the src of the img element. Use the jQuery attr to do this. You should append a timestamp parameter so the browser does not obtain a cached instance from the local browser cache.
function loadImg(src) {
// append a parameter of "_" to the url
$("#myimg").attr("src", src + "?_=" + Date.now());
}
setInterval(loadImg("path/to/img"), 1000);
On your PHP side you would need a script that servers the image up in your converted format from where ever you are storing it. An example of how to do that is here.
I've managed to come up with a solution using $.post instead of $.load. The function is called via:
setInterval(
function auto_refresh_img()
{
var img_path = document.getElementById("image_path").value;
$.post('refresh_img.php',
{path: img_path},
function(data) {
$('#my_div').html(data);}
);
}, 1000);
with refresh_img.php looking like this:
<?php $imagepath = $_REQUEST['path'];
if (file_exists($imagepath)) {
$img = new imagick($imagepath."[0]");
$img->setImageFormat('jpg');
$thumbnails0 = $img->getImageBlob();
echo "<img src='data:image/jpg;base64,".base64_encode($thumbnails0)."' id='reco_background' style='display:none' />";
}
else {
echo "Image does not exist.";
};
?>
The returned <img ... > may then be used for any purpose.
Here are my code:
<script type="text/javascript">
function SaveToDisk(fileUrl, fileName) {
var hyperlink = document.createElement('a');
hyperlink.href = fileUrl;
hyperlink.target = '_blank';
hyperlink.download = fileName || fileUrl;
var mouseEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
hyperlink.dispatchEvent(mouseEvent);
(window.URL || window.webkitURL).revokeObjectURL(hyperlink.href);
}
</script>
</head>
<body>
<?php
$newtarget = "0C004B290BF2D95F";
$filename = 'C:/Users/FOO/Downloads/'.$newtarget.'.txt';
if (file_exists($filename)) {
unlink($filename);
}
?>
<script type="text/javascript">
SaveToDisk('http://www.ticketmaster.com/json/resale?command=get_resale_listings&event_id=<?php print $newtarget; ?>','<?php print $newtarget; ?>.txt')
</script>
<?php
$newlink = file_get_contents('C:\\Users\\FOO\\Downloads\\'.$newtarget.'.txt');
When the file is deleted the file_get_contents php function runs before the SavetoDisk rewrite the file on disk.
"failed to open stream: No such file or directory".
When I don't delete the file, it works. I tried to insert sleep(10) right after the call of the javascript function but still got the error, inexplicably the file is wrote after the 10 seconds... any tips on this?
PHP is processed by your server whereas Javascript is processed by the user's browser, therefore regardless of how you order functions within the same .php doc, the Javascript will always run after the PHP is processed.
If you need to run PHP after your Javascript has been executed, look at jQuery's post function to call a PHP file from your Javascript. I'd strongly recommend you take a look at some online learning tools like codecademy to get a better grasp of PHP / JS.
You can't do that. PHP is executed on the server and JavaScript is executed on the client (web browser).
Right click on your web browser and select View Source to check the content. You will not see your PHP there.
Im trying to fetch my mysql data I've read some article in
https://developers.google.com/maps/documentation/javascript/examples/layer-heatmap
<?php
$locations = mysql_query("select * from locations");
?>
<?php
$lats = ""; // string with latitude values
$lngs = "";
while ($locat = mysql_fetch_array($locations))
{
$lats = $locat['latitude'];
$lngs = $locat['longitude'];
$taxiData = [new google.maps.LatLng($lats,$lngs)];
}
?>
instead of var taxiData = [new google.maps.LatLng(37.782551, -122.445368)];
now Im trying to fetch the value in those latitude and longitude.
You're trying to execute the js example in PHP. Really, U'll need to learn a bit about web development, but You can try something like this trying to make it working right now:
<?php /* You should add all needed external js scripts above */?>
<script type="text/javascript">
//Here You should put everything before the points array declaring from the example
<?php
$locations = mysql_query("select * from locations");
echo 'var taxiData = [';
while ($locat = mysql_fetch_array($locations))
echo "new google.maps.LatLng({$locat['latitude']}, {$locat['longitude']}),\n";
echo '];';
//Here You should put everything after the points array declaring from the example
?>
</script>
The code above is terrible, but the js part will be sent to the browser and the browser will try to execute it. Anyway, U should take a read a little about web development, otherwise a lot of simple things will be hard enough for You. Good luck.
You seem to be mixing php and javascript with abandon. If you want to issue a javascript command, you have to make sure it looks like javascript to the browser. Maybe something like
<?php
$locations = mysql_query("select * from locations");
?>
<?php
$lats = ""; // string with latitude values
$lngs = "";
while ($locat = mysql_fetch_array($locations))
{
$lats = $locat['latitude'];
$lngs = $locat['longitude'];
$taxiString = "new google.maps.LatLng($lats,$lngs)";
?>
<script type="text/javascript">
var taxiData = [<?=$taxiString?>];
// do whatever you want in javascript
</script>
}
?>
A tested snippet that demonstrates the idea (I could not test the above easily):
<html>
<?php
for($i=0;$i<2;$i++) {
$myString = "It works $i times!";
echo $myString;
?>
<script type="text/javascript">
alert("<?= $myString; ?>");
</script>
<?php
}
?>
</html>
When you run that you will see that the php string $myString was properly inserted into the JavaScript.
Let me clarify a little bit more.
Javascript is code that is executed by the BROWSER. php is code that is executed on the SERVER. The BROWSER will be asking Google Maps for some information - it is your task to make sure that the command that the browser issues is correct. php is nice in that it allows you to change the text that appears in the browser.
The way to understand the difference is to look at the source code of a web page in your browser. The second snippet I posted above is actually available on http://www.floris.us/SO/mix.php
When you open it in your browser, and you look at the source code, you will see
<html>
It works 0 times!<script type="text/javascript">
alert("It works 0 times!");
</script>
It works 1 times!<script type="text/javascript">
alert("It works 1 times!");
</script>
</html>
Breaking it down a little bit ( and adding some carriage returns for clarity):
<html> - this was text in my original file
It works 0 times! - this was the result of a php echo command
<script type="text/javascript"> - literal text in original file
alert(" - literal text
It works 0 times! - the result of <?= $myString; ?>
"); - literal text
</script> - literal text
And then something crazy - the same thing repeats (because of the php loop) - BUT WITH A DIFFERENT VALUE (1 instead of 0):
It works 1 times!<script type="text/javascript">
alert("It works 1 times!");
</script>
</html> - this last line did not repeat because it's outside the php loop
Final comment:
<?= $myString; ?>
is shorthand for
<?php echo $myString; ?>