Question:
How can I force-download a CSV file through an AJAX call in PHP?
Background:
You have created an AJAX function that generates a CSV file based on user input. After creation, you want to automatically download the file without prompting the user.
PHP Code:
In your PHP file (csv.php), you have attempted to use the following script to force download the CSV file:
<code class="php">$fileName = 'file.csv'; $downloadFileName = 'newfile.csv'; if (file_exists($fileName)) { header('Content-Description: File Transfer'); header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename='.$downloadFileName); ob_clean(); flush(); readfile($fileName); exit; } echo "done";</code>
Issue:
When you run this script at the end of csv.php, the contents of the file are displayed on the page instead of being downloaded.
Solution:
AJAX cannot be used for directly downloading files. To force download the file, you can use one of the following methods:
Example:
You can modify your AJAX function as follows to pop up a new window with the download link:
<code class="javascript">function csv() { ajaxRequest = ajax(); postdata = "data=" + document.getElementById("id").value; ajaxRequest.onreadystatechange = function () { var ajaxDisplay = document.getElementById('ajaxDiv'); if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) { window.open(ajaxRequest.responseText); // Pop up a new window with the download link } } ajaxRequest.open("POST", "csv.php", false); ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); ajaxRequest.send(postdata); }</code>
The above is the detailed content of How to Force-Download a CSV File Through AJAX in PHP?. For more information, please follow other related articles on the PHP Chinese website!