Skip to content
Advertisement

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement