Home > Backend Development > PHP Tutorial > How to Trigger a File Download Using AJAX: Direct Download or Server-Side Redirect?

How to Trigger a File Download Using AJAX: Direct Download or Server-Side Redirect?

Mary-Kate Olsen
Release: 2024-12-17 00:12:24
Original
948 people have browsed it

How to Trigger a File Download Using AJAX:  Direct Download or Server-Side Redirect?

Download File with AJAX Request

When attempting to initiate an "ajax download request" upon button click, it's common to implement code like the below:

var xhr = new XMLHttpRequest();
xhr.open("GET", "download.php");
xhr.send();
Copy after login

Along with the following PHP script:

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

However, this approach may not yield the desired result. To effectively initiate a download, consider implementing one of the following alternatives:

Option 1: Utilize the 'download' Attribute

In modern browsers like Firefox and Chrome, the 'download' attribute offers a convenient way to initiate downloads from within a webpage without requiring server-side interaction. Here's an example:

<a href="file.txt" download="file.txt">Download</a>
Copy after login

Option 2: Navigate to the Download Script using AJAX or Window.location

If the 'download' attribute isn't a suitable option, you can use AJAX or window.location to navigate to the download script. Using AJAX, you can perform an asynchronous request and then use its success callback function to redirect to the download script:

$.ajax({
    url: 'download.php',
    type: 'POST',
    success: function() {
        window.location = 'download.php';
    }
});
Copy after login

Alternatively, you can simply use window.location to navigate to the download script:

window.location = 'download.php';
Copy after login

While the AJAX approach provides some flexibility, using window.location is typically more efficient and straightforward.

The above is the detailed content of How to Trigger a File Download Using AJAX: Direct Download or Server-Side Redirect?. 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