Download File Via AJAX in PHP
In this scenario, you have a button that triggers an AJAX call to a PHP function, 'csv.php'. The PHP script generates a CSV file, and you desire to download it either promptly or forcibly upon completion.
The provided PHP code, when run within 'csv.php', outputs the file contents to the page rather than initiating a download. This occurs because AJAX is not natively designed for file downloads.
Solution:
To force a file download with PHP, you can employ the following technique:
Create a new window using JavaScript:
window.open("csv.php", "_blank");
Redirect the current document location (force download):
document.location = "csv.php";
This approach initiates a new HTTP request, prompting the browser to download the file. The desired header settings for download initiation are included within 'csv.php'.
The above is the detailed content of How Can I Force a File Download from a PHP Script Triggered by AJAX?. For more information, please follow other related articles on the PHP Chinese website!