Home >Web Front-end >JS Tutorial >Why Doesn't AJAX Work for File Downloads, and What's the Best Alternative?

Why Doesn't AJAX Work for File Downloads, and What's the Best Alternative?

Barbara Streisand
Barbara StreisandOriginal
2024-12-09 17:50:12654browse

Why Doesn't AJAX Work for File Downloads, and What's the Best Alternative?

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:

  • HTML5 introduces the 'download' attribute. It is supported by Firefox and Chrome, and soon to be included in IE11. It allows for direct file downloads on the same origin.

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':

  • Unlike AJAX requests, 'window.location' directly navigates to the file, triggering the download.

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!

Statement:
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