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

How to Force-Download a CSV File Through AJAX in PHP?

Susan Sarandon
Release: 2024-10-24 08:37:01
Original
223 people have browsed it

How to Force-Download a CSV File Through AJAX in PHP?

Downloading Files with PHP and AJAX

Question:

How can I force-download a CSV file through an AJAX call in PHP?

Background:

You have created an AJAX function that generates a CSV file based on user input. After creation, you want to automatically download the file without prompting the user.

PHP Code:

In your PHP file (csv.php), you have attempted to use the following script to force download the CSV file:

<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

Issue:

When you run this script at the end of csv.php, the contents of the file are displayed on the page instead of being downloaded.

Solution:

AJAX cannot be used for directly downloading files. To force download the file, you can use one of the following methods:

  • Pop up new window: Create a new window with the download link as its address.
  • document.location = ...: Use the document.location = ... property to set the current location of the document to the download link.

Example:

You can modify your AJAX function as follows to pop up a new window with the download link:

<code class="javascript">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) {
            window.open(ajaxRequest.responseText);  // Pop up a new window with the download link
        }
    }

    ajaxRequest.open("POST", "csv.php", false);
    ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajaxRequest.send(postdata);
}</code>
Copy after login

The above is the detailed content of How to Force-Download a CSV File Through AJAX in PHP?. 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!