title: How to save a file to the server by pressing a button in Javascript
body: <p>Ok so I'm experimenting with the  in HTML5 and have made a simple "paint" application in Javascript to draw where the user's mouse is on the screen. Works fine.</p>
  
  <p>I then wanted to save the coordinates to a file. My program already had an array of the x coordinates and an array of the y coordinates from the Javascript code.</p>
  
  <p>When the user presses a button, the onClick calls a function in the Javascript, which using jQuery, as in the Top Answer here <a href="https://stackoverflow.com/questions/419240/how-to-get-javascript-function-data-into-php-variable">How to get JavaScript function data into a PHP variable</a> attempts to pass this into a php file to save. </p>
  
  <p>However it isn't working. Should I be passing the data back into the original php document that contains the canvas? If so how do I then get it to do the code to save as the PHP is run when the document is loaded no?</p>
  
  <p>CODE:</p>
  
  <p>Ok this is in the original php file which contains the HTMl for the webpage including the canvas. Here's the relevant save button:</p>
  
  <p><code>&lt;button type="button" onclick="saveDrawing()" id="saveButton"&gt;Save&lt;/button&gt;</code></p>
  
  <p>This calls the following in a separate JS file</p>
  
  <pre><code>function saveDrawing(){
  // First check that not drawing and have data
  if (!readyToDraw &amp;&amp; clickX!=null){  
      // If ready then pass back to the PHP file the data
      $url = 'file_save_test.php';
      $.get($url, {x_coords: getXCoords(), y_coords: getYCoords()});
      }
  else {
      alert("Please add some coordinate points and press Finish before saving");
  }
  }
  </code></pre>
  
  <p>and file_save_test.php contains only the following</p>
  
  <pre><code>&lt;?php
  
  // retrieve data from the JS
  $buffer_data['x_coords'] = $_GET['x_coords'];
  $buffer_data['y_coords']  = $_GET['y_coords'];
  
  $x_s = $_GET['x_coords'];
  $y_s = $_GET['y_coords'];
  
  // first want to open a file
  $file_name = "data_test.txt";
  $file_handler = fopen($file_name, 'w');
  
  // now to loop through arrays and write!
  /*for ($i = 0; $i &lt; sizeof($x_s); i++){
      fwrite($file_handler, "$x_s[i], ");
      fwrite($file_handler, "$y_s[i]\n");
  } */
  
  
  fclose($file_handler);
  
  
  ?&gt;
  </code></pre>