Home >Backend Development >PHP Tutorial >How to Force a File Download Instead of Displaying its Contents Using AJAX and PHP?

How to Force a File Download Instead of Displaying its Contents Using AJAX and PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-05 06:45:11603browse

How to Force a File Download Instead of Displaying its Contents Using AJAX and PHP?

Downloading File Through AJAX Call PHP

Problem:

An Ajax function retrieves data from a PHP file. Despite using a PHP script to prompt a file download at the end of the script, the file's contents are instead displayed on the page. How can the file be forcefully downloaded?

Answer:

AJAX is not intended for file downloads. To force a file download, consider the following solution:

Use the JavaScript window.open() or document.location = methods to open a new window with the download link as the address.

Example Using window.open():

window.open('download.php?file=file.csv');

Example Using document.location:

document.location = 'download.php?file=file.csv';

Revised PHP Script:

$fileName = 'file.csv';
$downloadFileName = 'newfile.csv';

if (file_exists($fileName)) {
    // Determine the download script URL
    $downloadURL = 'download.php?file=' . $fileName;

    // Output JavaScript to open a new window with the download script URL
    echo '<script type="text/javascript">window.open("' . $downloadURL . '");</script>';
    exit;
}

This solution will prompt the download of the file.csv file without displaying its contents on the page.

The above is the detailed content of How to Force a File Download Instead of Displaying its Contents Using AJAX and 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