Javascript does not call file - javascript

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.

Related

Some trouble running a javascript function in an external file from php

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);

adding php stops my javascript init() working

I have a file written in html and javascript. I have an init function that I used to initialise some variables in javascript. To make this happen I have the following tag in the body statement:
<body onload="init()">
and then later I have the function itself. All seems to work well.
function init() {
// initialisation stuff here
var arr = ["happy", "winter", "hot", "cold", "male", "female", "summer", "spring", "autumn"];
document.getElementById('word').innerHTML = arr[Math.floor(Math.random() * arr.length)];
flag = 0;
}
However, I now want to load some data from a file so that I can replace the arr variable in my init() function with a much longer list of words. So just below the body statement I put the following:
<?php
$words = file('data.txt');
?>
I changed the file extension from html to php so that the php script would run before the page loads. When I change the extension to php it works fine. But as soon as I add those php lines I get an error. When I look using Develops Tools it says - Uncaught Reference Error: Init not defined.
But my init function is still there. Why would adding those php lines affect the javascript init function?
EDIT
I had the following two lines in my init function
// var words = <?php echo '["' . implode('", "', $words) . '"]' ?>;
// alert(words);
I thought they were commented out. But obviously not. If I remove them the code works fine.
However, although it is evident from the run-time inspection that
var words = <?php echo '["' . implode('", "', $words) . '"]' ?>;
alert(words);
is bringing the data into the init function, somehow it is still producing an error.

How to detect the new version of a Javascript file?

the problem is that I have a remote js file to include in a page and it has to be included the last version of it. To be more specific:
The file is for example: http://example.com/javascript/v03/header.js
The problem is that when they generate a new javascript file the url will be changed to http://example.com/javascript/v04/header.js for example.
The URL will be changed to a new version number.
My question is what will be the best/clean way to detect a new version of that file in Php?
Thank you!
Untested but should work.
You file_get_contents the versions and when it returns false you have gone to far.
$link = "http://example.com/javascript/VERSION/header.js";
For($i=1; $i<100; $i++){
$test= str_replace("VERSION", "v" . str_pad($i, 2, "0", STR_PAD_LEFT), $link);
If(file_get_contents($test)){
$latest = $test;
}else{
Break;
}
}
Echo "latest version is " . $latest;
Then optionally you save the $i number somewhere and use that the next time you run it so that you don't need to recheck version 1-4 every time.
EDIT, noticed I had $str instead of $link.

PHP filesize won't update; even with clearstatcache();

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.

Assigning latitude and longitude in MVCarray

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; ?>

Categories

Resources