Returning file contents using Ajax

I am trying to create a page where I can select a file to edit and get the file contents via Ajax. I have been trying to get my head round the syntax and I haven’t figured out how to actually return the file contents.

I currently have the following:

    $pages = array(
      'index' => 'Home',
      'contacts' => 'Contacts',
      'events' => 'Events',
      'history' => 'History'
    );
    ?>
    <form id="form" name="form" method="post">
      <div>
        <label for="file">Page to edit</label>
        <select name="file" id="file">
          <option selected disabled>--Select--</option>
          <?php
          foreach ($pages as $key => $page) {
            echo '<option value="', $key, '">', $page, '</option>', PHP_EOL;
          }
          ?>
        </select>
      </div>
      <div>
        <textarea name="contents" id="contents"></textarea>
      </div>
      <input type="submit" name="gandalf" value="Update">
    </form>
  <script>
  const select = document.getElementById("file");
  const fcontent = document.getElementById("contents");
  select.addEventListener("change", function() {
    const sfile = select.options[select.selectedIndex].value;
    fetch("getFileContents.php?f="+sfile)
    .then (response => {
      fcontent.innerHTML = "Waiting for response...";
      if (response.ok)
        return response;
      throw Error(response.statusText);
    })
    .then (response => response.text())
    .then (text => fcontent.innerHTML = text)
    .catch (error => console.log("There was an error:", error))
  });
  </script>

getFileContents.php

$f = $_GET['f'];
$file = '../md/'.$f.'.md';
if (file_exists($file)) {
  $text = file_get_contents($file);
}

I can echo $text; and it appears in my textbox, but I’m not sure that’s the way I’m supposed to do it. Or is it… :shifty:

You’re forgetting to return something from your PHP script.

Change this:

$f = $_GET['f'];
$file = '../md/'.$f.'.md';
if (file_exists($file)) {
  $text = file_get_contents($file);
}

To this:

$f = $_GET['f'];
$file = '../md/'.$f.'.md';
if (file_exists($file)) {
  $text = file_get_contents($file);
}
echo $text;

And all will be well.

Thanks squire. That’s what I did in the end. I wasn’t sure if it was the right way to return a value - it seems an odd way to return a value. I’m glad you have confirmed that’s how to do it! :smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.