简体   繁体   中英

Change Website Content with PHP and AJAX Without Page Reload

A server process changes the content of a file readme.txt which is located in a users home directory (Linux Ubuntu 20.04 Server). I want to reflect the file content on the page without fully reloading the site. Therefore I tried AJAX in the index.php file:

<!DOCTYPE html>
<html>
<head>
<title>Read a File</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>

<?php
  $reader = file_get_contents("/userhome/readme.txt");
  echo $reader;
?>

<script type="text/javascript"> 
function readFile() { 
    $.get("index.php"); 
    return false; 
} 
</script>
  
<button onclick="readFile()">Click me</button>

</body>
</html>

Shouldn't an AJAX GET request to the PHP file itself load the new content and display it on the page?

reader.php

<?php
  $reader = file_get_contents("/userhome/readme.txt");
  echo $reader;
?>

So basically after clicking the Read me button, the div with id read will be filled with the txt content

index.php

    <!DOCTYPE html>
    <html>
    <head>
    <title>Read a File</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    </head>
    <body>
    

    <div id="read">

</div>
    <script type="text/javascript"> 
    $(document).ready(function(){
      $("#load").click(function(){
        $("#read").load("reader.php");
      });
    });
    </script>
      
    <button id="load">Read me</button>
    
    </body>
    </html>

there are many other solutions for this

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