Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-10-24 08:35:02
Original
756 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!