1

So I'm doing an operation inside the javascript to attribute a javascript variable to a php value that is obtained via txt file. But I want to repeatedly refresh. I've seen a few questions on this website like this one but didn't do the trick for me.

PHP code:

<?php
 $file = "nam.txt"; //Path to your *.txt file
 $contents = file($file);
 $nam = implode($contents);
?>

Javascript code (with setinterval but for now that is not working):

setInterval(function(){
 document.getElementById("nam").innerHTML = '<?php echo $nam; ?>';
}, 50);
  • Fyi, those are 50 miliseconds. Do you really want to update that fast? – brombeer Jun 27 '18 at 11:29
  • 2
    This sounds like an [X-Y Problem](http://xyproblem.info/), especially with that 50 mS interval. What is it you want to achieve exactly? – Loek Jun 27 '18 at 11:30
  • I know, I just assimilated it randomly so you get what I want, is to use setInterval but for the PHP variables. – Miguel Casanova Jun 27 '18 at 11:30
  • 1
    For now it just prints `$nam`, not reloading the `nam.txt`. – brombeer Jun 27 '18 at 11:32
  • I know, that is what I want to do and Can't get it to work. I think it's possible with AJAX but no idea how to do it. – Miguel Casanova Jun 27 '18 at 11:34
  • How should that work? PHP runs on the server, JS in the browser. Probably, you want to refresh the data using an AJAX request? – Nico Haase Jun 27 '18 at 11:34
  • Google how to do it with ajax if you have no idea how to then come back with an issue you run into there. – Dellirium Jun 27 '18 at 11:34
  • @MiguelCasanova The easiest solution I can think of is indeed AJAX. If you have no idea how that works, it might be easier to follow a couple of online courses or tutorials since AJAX is pretty basic knowledge in web development. No offense, we all started like that! – Loek Jun 27 '18 at 11:35
  • I googled it and couldn't get it to work because it was way too much different from my problem and couldn't assimilate both. I want to refresh the data using AJAX, just don't know why. – Miguel Casanova Jun 27 '18 at 11:36
  • @MiguelCasanova Feel free to comment down the problem you face in implementing the method i've mentioned in my answer – Yash Kumar Verma Jun 27 '18 at 12:59

1 Answers1

2

The Problem

PHP is evaluated only when the request is made to the server, and once the server sends the response (sending the data of the .txt file), even if the contents of the file change, it cannot be retrieved (unless another request is made to the server)

Solution

In the setInterval function, make an ajax request to some page, and program that page to return the contents of the file. This way you can update the page in real-time as well as get the updated content after page load as well.

If you're new to AJAX, this might be helpful

Ajax tutorial for post and get

Yash Kumar Verma
  • 9,427
  • 2
  • 17
  • 28