I figured out how to read a local .TXT file on the server into JS using the XMLHttpRequest API but for the life of me I cant get it to write to the file. Is it possible or is this only for reading the files in?
My code to read in works fine:
var fReader = new XMLHttpRequest();
fReader.onreadystatechange=function() {
if(fReader.readyState==4 && fReader.status==200) {
parseText(fReader.responseText);//Processes the file.
}}
fReader.open("GET",fFileLoc,true);
fReader.send();
I'm currently using PHP to write to the file, but it's far from ideal. I'd really like to us JS to do it. Any thoughts? Is there another approach to doing this? Is PHP the only way?
Thanks in advance,
-Dave
EDIT: @rjmunro +others: I found that using PHP was the better way to go about this... My revised code is as follows. (C&C welcome).
JS:
var fReader = XMLHttpRequest();
//var params = "MODE=GET&File=Data.txt";//To read
//var params = "MODE=POST&File=Data.txt&Message=" + myMessage;//To write
fReader.onreadystatechange=function() {
if(fReader.readyState==4 && fReader.status==200) {
//Not really any response text if writing...
parseText(JSON.parse(fReader.responseText).GET);
}
}
fReader.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
fReader.setRequestHeader("Content-length", params.length);
fReader.setRequestHeader("Connection", "close");
fReader.send(params);
PHP
$MODE = $_POST['MODE'];
switch($MODE) {
case('GET'):
#Read in file and process, then return output.
$return['GET'] = file($_POST['File']);
break;
case('POST'):
if(file_exists($_POST['File'])){
$file = fopen($_POST['File'],"a");
$data = $_POST["Message"];
fwrite($file,$data);
fclose($file);
}
#$return['POST'] = "some message?";
break;
}
echo json_encode($return);
The only thing i'm not 100% on with this solution is why i have to setRequestHeader? Chrome actually doesnt seem to like this... I pulled the code from another post.
XMLHttpRequestand finally use PHP to write to file. Yes, php us required to write to file.