0

Trying to read a small text file in php into a js variable. But the alert shows nothing even though the contents of "tmp/data.txt" = 30086895

function sort_rating() {reset_colors(); read_reg; 
myArray = myArray.sort(function(a, b){ return b.rate - a.rate;}); fortify(); newcomers();}

function newcomers() {
// data = '<?php clearstatcache(); echo readfile("tmp/data.txt"); ?>'; alert(data);
data = '<?php clearstatcache(); echo file_get_contents("tmp/data.txt"); ?>'; alert(data);
}

How can I make this work, please?

verlager
  • 794
  • 5
  • 25
  • 43
  • By actually _outputting_ the return value of `file_get_contents` maybe …? – CBroe May 10 '21 at 10:56
  • Can you share your complete code ? – Omar May 10 '21 at 11:02
  • Sorry, I corrected the "echo" omission. The script works only the first time. As new data is appended to "tmp/data.txt" I would hope to read that in, and process the contents. The "clearstatcache();" should help to show the current contents, but it doesn't. What can I do? – verlager May 10 '21 at 11:05
  • Sure I will append some code to original post. – verlager May 10 '21 at 11:07
  • 1
    Re: _The script works only the first time._ PHP only runs once. It runs on the server as the HTTP response is being prepared and sent back to the client. If you want more sophisticated client-server interaction without actually doing a full page-reload, then the Javascript [`Fetch API`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) will be able to repeatedly interrogate a server-side PHP script. But, that said, instead of `tmp/data.txt`, you might find it easier to use client-side storage like [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). – Rounin May 10 '21 at 11:09
  • What does the HTML/JS code this creates look like? I am guessing your “appending” to the text file means adding multiple _lines_ to it? Well then you would simply be violating the JS syntax rules for text literals delimited by single quotes (and a look into the browser console should have alerted you to that), which can’t contain newlines directly. (https://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript) – CBroe May 10 '21 at 11:21
  • Required reading: [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) . It doesn't matter how many times you re-run the Javascript within one page, the output that was generated by PHP is static - from the browser's point of view, it never sees the PHP code (because that runs once on the server, _before_ the page gets anywhere near the browser), it just sees the _output_ from the PHP, as if it had been hard-coded. – ADyson May 10 '21 at 11:27
  • 1
    Great news! The fetch command was easy and effective, Thank you so much for putting me on the correct path, @Rounin – verlager May 10 '21 at 12:05

0 Answers0