title: Download file through an ajax call php
body: <p>I have a button and <code>onclick</code> it will call an ajax function. </p>
  
  <p>Here is my ajax function</p>
  
  <pre><code>function csv(){
  
      ajaxRequest = ajax();//ajax() is function that has all the XML HTTP Requests
  
      postdata = "data=" + document.getElementById("id").value;
  
      ajaxRequest.onreadystatechange = function(){
          var ajaxDisplay = document.getElementById('ajaxDiv');
          if(ajaxRequest.readyState == 4 &amp;&amp; ajaxRequest.status==200){
              ajaxDisplay.innerHTML = ajaxRequest.responseText;           
          }
      }
  
      ajaxRequest.open("POST","csv.php",false);
      ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      ajaxRequest.send(postdata);
  }
  </code></pre>
  
  <p>I create the csv file based on the user input. After it's created I want it to prompt download or force download(preferably force). I am using the following script at the end of the php file to download the file. If I run this script in a separate file it works fine. </p>
  
  <pre><code>$fileName = 'file.csv';
  $downloadFileName = 'newfile.csv';
  
  if (file_exists($fileName)) {
      header('Content-Description: File Transfer');
      header('Content-Type: text/csv');
      header('Content-Disposition: attachment; filename='.$downloadFileName);
      ob_clean();
      flush();
      readfile($fileName);
      exit;
  }
  echo "done";
  </code></pre>
  
  <p>But If I run it at the end of csv.php it outputs the contents of the file.csv into the page(into the ajaxDiv) instead of downloading. </p>
  
  <p>Is there a way to force download the file at the end of csv.php?</p>