Downloading Files with AJAX Requests: A Comprehensive Guide
Problem: Attempting to initiate an "ajax download request" upon button click does not yield the desired results. A demonstration in JavaScript and PHP is provided below:
JavaScript:
var xhr = new XMLHttpRequest(); xhr.open("GET", "download.php"); xhr.send();
PHP (download.php):
<? header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename= file.txt"); header("Content-Transfer-Encoding: binary"); readfile("file.txt"); ?>
The above code is not functioning as anticipated. Can you provide insights into the necessary steps to resolve this issue?
Solution:
Initiating a file download through an AJAX request is not feasible. For this task, direct access to the file is required.
Updated Solution (April 27, 2015):
Use 'download' Attribute:
JavaScript:
// Check if 'download' is supported if ('download' in HTMLAnchorElement.prototype) { // Create an anchor element var anchor = document.createElement('a'); // Set 'download' attribute and file URL anchor.download = 'file.txt'; anchor.href = 'download.php'; // Trigger file download anchor.click(); } else { // Fallback to previous method window.location = 'download.php'; }
Original Solution:
Use 'window.location':
JavaScript:
$.ajax({ url: 'download.php', type: 'POST', success: function() { window.location = 'download.php'; } });
For simplicity, it is recommended to avoid the AJAX request altogether and simply use 'window.location'.
The above is the detailed content of Why Doesn't AJAX Work for File Downloads, and What's the Best Alternative?. For more information, please follow other related articles on the PHP Chinese website!