I'm experimenting with PHP together with Ajax and JQuery to make a site where I can write to a text file and then have the site load the textfile's contents into a div.
This is the JQuery code I'm using.
$(document).ready(function() {
setInterval(function() {
$("#text").load("storydoc.txt");
}, 2000);
});
And here is the PHP together with the relevant HTML.
<div id="text">
</div>
<form id="form" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input id="wordinput" class="input" type="text" name="word" maxlength="30"></input>
<input id="submit" class="hidden" type="submit" name="submit"></input>
</form>
<?php
if(isset($_POST['submit'])) {
$word = " " . $_POST['word'];
$ret = file_put_contents('text.txt', $word, FILE_APPEND | LOCK_EX);
if($ret === false) {
die("There was an error writing this file");
}
}
?>
So what it does is it lets the user write to "text.txt" using #wordinput and than updates #text with .load() to show the new updated text from "text.txt". This text can then be seen and written to by other users as well.
The problem I'm having is that the text file can show different contents on different browsers. If I for example open up the site in Firefox and write something to the text.file, it won't show. Even if I go to the file itself inside the cPanel file manager it still shows the text as it were when I got on the site. If I then open up Chrome and go to the site there, it will show the new updated text on both the site and file manager. Writing more words also instantly shows on the site in Chrome. Meanwhile Firefox is still showing the same outdated textfile contents even after refreshing. After this it works perfectly on all browsers but the one who first opened up the file first. Then if you leave the text file unedited for some time I get the same problem again, having to switch browser.
It works the same way the other way around, starting with Chrome, so I don't think it has anything to do with a specific webbrowser. To me it seems like the browser who first opens up "text.txt" saves a copy of it and only uses that one from there on out, and I have no clue how to solve it.
Any solutions or ideas are welcomed! Thank you in advance!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…