title: Use JavaScript to write data in a text file
body: <p>I'm working on a project to make sure that users finish a video. I would like to have it just add something like "user has finished video" to an already existing text file. 
  Here is what I have in my JavaScript file. </p>
  
  <pre><code>    var video = document.getElementById("video");
  
  var timeStarted = -1;
  var timePlayed = 0;
  var duration = 0;
  // If video metadata is laoded get duration
  if (video.readyState &gt; 0)
  getDuration.call(video);
  //If metadata not loaded, use event to get it
  else {
  video.addEventListener('loadedmetadata', getDuration);
  }
  // remember time user started the video
  function videoStartedPlaying() {
  timeStarted = new Date().getTime() / 1000;
   }
  
  function videoStoppedPlaying(event) {
  // Start time less then zero means stop event was fired vidout start event
  if (timeStarted &gt; 0) {
      var playedFor = new Date().getTime() / 1000 - timeStarted;
      timeStarted = -1;
      // add the new ammount of seconds played
      timePlayed += playedFor;
  }
  document.getElementById("played").innerHTML = Math.round(timePlayed) + "";
  // Count as complete only if end of video was reached
  if (timePlayed &gt;= duration &amp;&amp; event.type == "ended") {
      document.getElementById("status").className = "complete";
  }
  }
  
  function getDuration() {
  duration = video.duration;
  document.getElementById("duration").appendChild(new Text(Math.round(duration) + ""));
  console.log("Duration: ", duration);
  }
  
  video.addEventListener("play", videoStartedPlaying);
  video.addEventListener("playing", videoStartedPlaying);
  
  video.addEventListener("ended", videoStoppedPlaying);
  video.addEventListener("pause", videoStoppedPlaying);
  
  
  
  var data = "This user has finished the video";
  var url = "data.php";
  var http = new XMLHttpRequest();
  http.open("POST", url, true);
  
  //sends hearder info along with the request
  http.setRequestHeader("content-type", "application/x-www-form-urlencoded");
  
  http.onreadystatechange = function() {
  if (http.readyState == 4 &amp;&amp; http.status == 200) {
      alert(http.responseText);
  
  }
  }
  http.send(data);
  </code></pre>
  
  <p>and Data.php has</p>
  
  <pre><code>    &lt;?php
      $data = $_POST['data'];
      $file = fopen('names.txt', 'a');
      fwrite($file, $data);
      fclose($file);
      ?&gt;
  </code></pre>
  
  <p>As of now, there are no errors in the console, but it does not write the data to the text file. </p>
  
  <p>Please let me know what i'm doing wrong</p>