Home >Web Front-end >JS Tutorial >How Can I Trigger a File Download with a Button Click Using AJAX?
In this article, we address a common question that arises when using AJAX requests: "How can I initiate a file download upon button click?"
To begin with, the provided code attempts to trigger a file download using an AJAX request to "download.php." However, this approach falls short as AJAX requests cannot directly initiate downloads.
Instead, there are two alternative solutions:
Using a Success Function:
In this method, an AJAX request is made, and upon successful completion, the browser is redirected to "download.php" to prompt the download.
$.ajax({ url: 'download.php', type: 'POST', success: function() { window.location = 'download.php'; } });
Using window.location (Recommended):
This is the most straightforward approach and involves bypassing the AJAX request altogether by directly navigating to the download URL.
window.location = 'download.php';
It's worth noting that browsers now support the download attribute, which simplifies file downloads and eliminates the need for AJAX or window navigation. However, its compatibility may vary across browsers.
The above is the detailed content of How Can I Trigger a File Download with a Button Click Using AJAX?. For more information, please follow other related articles on the PHP Chinese website!