I have a button and onclick
it will call an ajax function.
Here is my ajax function
function csv(){ ajaxRequest = ajax();//ajax() is function that has all the XML HTTP Requests postdata = "data=" + document.getElementById("id").value; ajaxRequest.onreadystatechange = function(){ var ajaxDisplay = document.getElementById('ajaxDiv'); if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){ ajaxDisplay.innerHTML = ajaxRequest.responseText; } } ajaxRequest.open("POST","csv.php",false); ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); ajaxRequest.send(postdata); }
I create the csv file based on the user input. After it's created I want it to prompt download or force download(preferably force). I am using the following script at the end of the php file to download the file. If I run this script in a separate file it works fine.
$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";
But If I run it at the end of csv.php it outputs the contents of the file.csv into the page(into the ajaxDiv) instead of downloading.
Is there a way to force download the file at the end of csv.php?
AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
AJAX isn't for downloading files. Pop up a new window with the download link as its address, or do document.location = ...
.
A very simple solution using jQuery:
on the client side:
$('.act_download_statement').click(function(e){ e.preventDefault(); form = $('#my_form'); form.submit(); });
and on the server side, make sure you send back the correct Content-Type
header, so the browser will know its an attachment and the download will begin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With