Download CSV file using “AJAX”

If you are forcing a download, you can redirect the current page to the download link. Since the link will generate a download dialog, the current page (and its state) will be kept in place.

Basic approach:

$('a#query_name').click(function(){
    $('#wait-animation').show();
    document.location.href="https://stackoverflow.com/php_scripts/utils/csv_export.php?query_name="+query_name;
    $('#wait-animation').hide();
});

More complicated:

$('a#query_name').click(function(){
    MyTimestamp = new Date().getTime(); // Meant to be global var
    $('#wait-animation').show();
    $.get('/php_scripts/utils/csv_export.php','timestamp='+MyTimestamp+'&query_name="query_name,function(){
        document.location.href = "https://stackoverflow.com/php_scripts/utils/csv_export.php?timestamp="+MyTimestamp+'&query_name="+query_name;
        $("#wait-animation').hide();
    });
});

At PHP script:

@header("Last-Modified: " . @gmdate("D, d M Y H:i:s",$_GET['timestamp']) . " GMT");
@header("Content-type: text/x-csv");
// If the file is NOT requested via AJAX, force-download
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    header("Content-Disposition: attachment; filename=search_results.csv");
}
//
//Generate csv
//
echo $csvOutput
exit();

The URL for both requests must be the same to trick the browser not to start a new download at document.location.href, but to save the copy at the cache. I’m not totally sure about it, but seems pretty promising.

Leave a Comment