Home > Web Front-end > JS Tutorial > How Can I Trigger File Downloads with Ajax Requests?

How Can I Trigger File Downloads with Ajax Requests?

Mary-Kate Olsen
Release: 2024-12-19 14:56:09
Original
896 people have browsed it

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

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

2. HTML5 Download Attribute

For modern browsers, the HTML5 download attribute can be employed:

<a href="download.php" download>
  Download File
</a>
Copy after login

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!

source:php.cn
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