title: Write to file in JS using XMLHttpRequest?
body: <p>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?</p>
  
  <p>My code to read in works fine:</p>
  
  <pre><code>var fReader = new XMLHttpRequest();
  
  fReader.onreadystatechange=function() {
    if(fReader.readyState==4 &amp;&amp; fReader.status==200) {
      parseText(fReader.responseText);//Processes the file.
  }}
  fReader.open("GET",fFileLoc,true);
  fReader.send();
  </code></pre>
  
  <p>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?</p>
  
  <p>Thanks in advance,</p>
  
  <p>-Dave</p>
  
  <p><strong>EDIT:  @rjmunro +others:</strong>  I found that using PHP was the better way to go about this...  My revised code is as follows.  (C&amp;C welcome).</p>
  
  <p>JS:</p>
  
  <pre><code>var fReader = XMLHttpRequest();
  //var params = "MODE=GET&amp;File=Data.txt";//To read
  //var params = "MODE=POST&amp;File=Data.txt&amp;Message=" + myMessage;//To write
  
      fReader.onreadystatechange=function() {
          if(fReader.readyState==4 &amp;&amp; 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);
  </code></pre>
  
  <p>PHP</p>
  
  <pre><code>$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);
  </code></pre>
  
  <p>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.</p>