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…