Home  >  Article  >  Web Front-end  >  How to Force Download a CSV File After Creation with PHP and AJAX?

How to Force Download a CSV File After Creation with PHP and AJAX?

Susan Sarandon
Susan SarandonOriginal
2024-10-24 08:35:02757browse

How to Force Download a CSV File After Creation with PHP and AJAX?

How to Download a File via AJAX in PHP

When working with web applications, it's often necessary to download files from the server. AJAX (Asynchronous JavaScript and XML) provides a way to initiate such downloads without reloading the page.

One method involves creating a button that triggers an AJAX function. The following code snippet demonstrates this approach:

<code class="php">function csv(){
  $ajaxRequest = ajax();
  $postdata = "data=" . document.getElementById("id").value;
  $ajaxRequest.onreadystatechange = function(){
    var ajaxDisplay = document.getElementById('ajaxDiv');
    if($ajaxRequest.readyState == 4 && $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>

However, the question here is how to force download a created CSV file after it has been created by PHP. The provided script in the PHP file is as follows:

<code class="php">$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>

The problem is that running this script doesn't initiate a download but instead displays the contents of the CSV file within the page (inside the ajaxDiv).

The answer to this issue is that AJAX is not intended for file downloads. Instead, the best practice is to open a new window and set its address to the download link. Alternatively, you can directly redirect the page to the download link using document.location = .....

The above is the detailed content of How to Force Download a CSV File After Creation with PHP and AJAX?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn