I\'m using the following script to initiate file downloads:
if (file_exists($newfilename)) {
header(\'Content-Description: File Transfer\');
header(\
It is possible to download a file using AJAX.
javascript:
function exportToCsv(){
var xmlhttp;
if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest; }else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
window.location="download.php?filename=export.csv";
}
}
}
request = "exportToCsv.php";
xmlhttp.open("GET", request, true);
xmlhttp.send();
}
The code above, exports a mysql database of contacts to a .csv file. After that, if everything is Ok (xmlhttp.readyState == 4)
automatically starts the download. window.location="download.php?filename=export.csv";
download.php file:
After this, the browser just presents the "Save file as" dialog, and no page refresh happens whatsoever. I have the application up and running, and never had problems. Runs on the following browsers:
Chrome v37.0.2062.120
Firefox v32.0.1
Opera v12.17
Internet Explorer v11