title: Generate and download CSV file with php and ajax
body: <p>I have a <code>php</code> page that creates a CSV file that is then downloaded by the browser automatically. Here is a version with sample data - it works great.</p>
  
  <pre><code>&lt;?php
  
  $cars = array(
    array("Volvo",22,18),
    array("BMW",15,13),
    array("Saab",5,2),
    array("Land Rover",17,15)
    );
  
  // output headers so that the file is downloaded rather than displayed
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename=csvfile.csv');
  
  // create a file pointer connected to the output stream
  $output = fopen('php://output', 'w');
  
  // output the column headings
  fputcsv($output, array('Car', 'Year', 'Miles' ));
  
  //Loop through the array and add to the csv
  foreach ($cars as $row) {
      fputcsv($output, $row);
  }
  
  ?&gt;
  </code></pre>
  
  <p>I would like to be able to run this from another page using <code>ajax</code> so that a user can generate/download a <code>csv</code> without leaving the main page. This is the <code>JavaScript</code> I am using on the main page. In my real page I am using the data coming via ajax.</p>
  
  <pre><code>$('button[name="exportCSVButton"]').on('click', function() {
      console.log('click');
      $.ajax({
          url: 'exportCSV.php',
          type: 'post',
          dataType: 'html',
          data: {
  
              Year: $('input[name="exportYear"]').val()
          },
          success: function(data) {
              var result = data
              console.log(result);
  
  
          }
      });
  });
  </code></pre>
  
  <p>When I click the button to trigger the script, it runs, but instead of saving/download to <code>csv</code> it prints the entire thing to console. Is there any way to accomplish what I want? Without actually saving the file to the server and reopening.</p>