Home >Web Front-end >JS Tutorial >How Can I Trigger File Downloads with Ajax Requests?
Downloading Files with Ajax Requests
Implementing a functionality to download files upon clicking a button using Ajax might encounter challenges. Let's explore a solution to overcome these obstacles.
Initial Attempt
An initial attempt to achieve this involves creating an XMLHttpRequest and sending a GET request to a PHP script, as shown below:
javascript: var xhr = new XMLHttpRequest(); xhr.open("GET", "download.php"); xhr.send(); 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"); ?>
Limitations
However, this method falls short due to browser constraints. Ajax requests cannot directly trigger the download prompt; instead, one must navigate to the file for it to occur.
Solution
Two approaches are available:
1. Use of window.location and Fallback
Utilize the window.location property to navigate to the download script, triggering the download:
$.ajax({ url: 'download.php', type: 'POST', success: function() { window.location = 'download.php'; } });
2. HTML5 Download Attribute
For modern browsers, the HTML5 download attribute can be employed:
<a href="download.php" download> Download File </a>
Note:
- The download attribute is only supported in Chrome, Firefox, and later versions of Internet Explorer.
- Ensure that the file to be downloaded is from the same origin as the host page.
The above is the detailed content of How Can I Trigger File Downloads with Ajax Requests?. For more information, please follow other related articles on the PHP Chinese website!