I have a php script that watches for the newest json file in a directory (below). Then in a javascript I parse and display the data from that file. The javascript reloads the data every x minutes.
I won’t have the name of the file just that it will contain json data and to use the newest one.
The PHP script stores the most recent file stored in array fileList[0]. I want to pass that to the javascript without a full page refresh so I checked this stackoverflow post and found that an ajax call can be made to a php script but the example updates an element on the page.
Is there a way to update a javascript variable? I thought of maybe placing the filename as a hidden element and the grabbing before I refresh the data, but that seemed crude.
<?php
date_default_timezone_set('America/New_York');
$files = glob('json/*.*', GLOB_BRACE);
usort($files, 'filemtime_compare');
function filemtime_compare($a, $b)
{
return filemtime($b) - filemtime($a); // Order newest to oldest
}
$i = 0;
$show = 1; // Number of new files to show.
$fileList = array();
foreach($files as $file)
{
if($i == $show) break; else ++$i;
array_push($fileList, $file);
}
//echo $fileList[0] // DEBUG: Make sure I have the right file.
?>
AJAX:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
// This will send a request to a PHP page
$.ajax({
var jsonURL = "";
url: "phpDir.php",
dataType: "html",
success: function(data){
// Place the returned data into your content
}
jsonURL = $fileList[0];
});
</script>
</head>
<body>
To answer your question “Is there a way to update a javascript variable?”
You would do this:
For ease of communication I have set the dataType to JSON. So PHP output would need to be json_encoded()ed: