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
Release: 2024-12-05 06:45:11
Original
591 people have browsed it

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');
Copy after login

Example Using document.location:

document.location = 'download.php?file=file.csv';
Copy after login

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

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 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