Home  >  Article  >  Web Front-end  >  How to Force-Download a CSV File Through AJAX in PHP?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-24 08:37:01224browse

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>

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>

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!

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