I have a simple AJAX function being called when a user clicks a button that sends the text of a HTML textarea and alerts the response from the backend:
send_button.onclick = function ()
{
var ajax = new XMLHttpRequest();
var text = text_input.value;
ajax.onreadystatechange = function ()
{
if (ajax.readyState == 4 && ajax.status == 200) alert(ajax.responseText);
};
ajax.open("POST", "write.php", true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.send("text=" + text);
};
as well as a PHP script on the backend which is supposed to write the received text to a file and echo the file's content:
<?php
$filename = "preview/preview.html";
$text = (isset($_POST["text"]) ? $_POST["text"] : "");
try
{
$fh = fopen($filename, "w+");
if (!$fh) throw new Exception("File open error");
fwrite($fh, $text);
$filetext = (filesize($filename) > 0 ? fread($fh, filesize($filename)) : "");
echo $filetext;
fclose($fh);
}
catch (Exception $e)
{
header("Location: error.php");
}
?>
But every time the response is empty. I tried echoing a hardcoded string instead of fread()and it worked, I also tried echoing filesize($filename)which worked perfectly fine as well.
The POST data sent by the AJAX function gets through as well, and the fwrite($fh, $text) function does exactly what it is supposed to.
What am I doing wrong?
You didn't rewind your file:
Why not use something more like this:
file_put_contents('preview/preview.html', $_POST['text'], FILE_APPEND);
readfile('preview/preview.html');
The "can't read file" is all fine and dandy, but all of the open/write/read business is redundant and can be reduced to the above two lines of code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With