File download script doesn't work when called from Ajax

Solution 1:

You cannot use AJAX to download files. It doesn't make sense. You can send the AJAX request and fetch the file contents inside the success handler on the client, but for obvious security reasons you can't do much with it. You cannot save it on the client computer and there's no javascript API allowing you to prompt the user where to save it.

So to download files, don't use AJAX. Create an anchor pointing to your server side script that serves the file to be downloaded.

Solution 2:

javascript cannot download files as its a security issue.

Solution 3:

AJAX requests does not served the same that other browser HTTP request do. You need only to put a link to your script with desired parameters, using about="_blank" or something like this. Modern browsers serve that well.

Solution 4:

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:

<?php

    $file = $_GET['filename'];

    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=".$file."");
    header("Content-Transfer-Encoding: binary");
    header("Content-Type: binary/octet-stream");
    readfile($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