Generate and Download CSV File With PHP and Ajax

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 = '/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 = '/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.

How to download CSV file from PHP script via AJAX?

Further to my comment(s), I would make the form able to submit normally or using ajax. Ajax for search, normal submit for download:

<div class="container">
<!-- Make this a proper form tag again -->
<form id="ldap-form" method="post" action="working_csv.php">
<h2><strong><p>Search the LDAP server</p></strong></h2>
<label for="location"><p>Enter your search location (ex: dc=example,dc=com)</p></label>
<input type="text" id="location" name="location" placeholder="Search Location.." />
<label for="filter"><p>Enter your search filter(s) (ex: uid=* or </p></label>
<input type="text" id="filter" name="filter" placeholder="Filter(s).." />
<input type="submit" name="search" id="search" value="Search LDAP Server" />
<input type="submit" name="download" id="download" value="Download results as CSV file" />
</form>
<!-- Response container -->
<p id="msg"></p>
</div>

<script>
$(function(){
$('input[type="submit"]').on('click', function(e){
// Stop form from submission
e.preventDefault();
// Detect button press type
let thisSubmission = $(this).attr('name');
// If the button is search, do ajax
if(thisSubmission == 'search') {
$.ajax({
type: "post",
url: $('#ldap-form').attr('action'),
data: $('#ldap-form').serialize(),
cache: false,
success: function(html){
$('#msg').html(html);
}
});
}
else {
// Just submit the form normally
$('#ldap-form').submit();
}
});
});
</script>

Why download a csv generated by PHP with Ajax add a 0 to the end of the file?

I've found the solution by myself.
In php, instead of return; conclude function with die().
Like this:

function ajax_export() {
$strFile = "Test";
header("HTTP/1.1 200 OK");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0",false);
header("Cache-Control: private", false);
header('Content-Type: text/csv; charset=utf-8');
header("Content-Disposition: attachment; filename=\"stats.csv\"");
echo $strFile;
die();
}


Related Topics



Leave a reply



Submit