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!