简体   繁体   中英

PHP saving textfile and showing it afterwards on another page doesn't work every time

I am using a HTML-form to write something and save it into a text file with PHP. After that I want to redirect the user to another page and show the written text file. Sometimes it works immediatly, but sometimes you still see the old content of the text file and have to reload the page to see the updated content. I'm fairly new in working with php, so I don't know how to fix this issue.

HTML-form is something like:

<form action="editor.php" method="post">
  <textarea name="textarea" id="textarea" placeholder="Text here ..."></textarea>
  <br><input type="submit" value="Save">
</form>

editor.php:

<?php
  $handle = fopen ( "news.txt", "w" );
  fwrite ( $handle, $_POST['textarea'] );
  fclose ( $handle );
  header("Location: index.html");
  exit;
?>

index.html:

<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function () {
      $.ajax({
        url : "news.txt",
        dataType: "text",
        success : function (data) {
          $("#text").html(data);
        }
      });
    });
</script>

<div id="text"></div>

Any ideas?

You have to cheat the browser in order to force it to download the very last by passing the cache argument to ajax call which appends a query string to the text file which your web browser should ignore :

<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function () {
      $.ajax({
        url : "news.txt",
        dataType: "text",
        cache : true,
        success : function (data) {
          $("#text").html(data);
        }
      });
    });
</script>

<div id="text"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM