Reputation: 151
I'm trying to build a "Export to CSV" system using ajax so this is my ajax call
$(document).on('click', '#export-csv', function(){
$.ajax({
url: export_url,
type: 'post',
data:{ validations: validations },
dataType: 'json',
cache: false,
timeout: 1000000,
success: function (data) {
var resp = data.response;
console.log(resp);
},
error: function (error) {
console.log(error);
}
});
});
and this is my php code to convert an array to csv
public function exportCsvAction()
{
$request = $this->getRequest();
if ($request->isPost()) {
$input = $request->getPost();
$response = $this->getResponse();
$file = fopen('php://output', 'w');
foreach ($input['validations'] as $line) {
fputcsv($file, $line, chr(9), '"');
}
fclose($file);
header('Content-type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="validations-' . time() . '.csv"');
return $response->setContent(\Zend\Json\Json::encode(array('response' => true)));
}
return $this->getResponse()->setStatusCode(400);
}
Everything is working. My ajax returns success but now I'm stuck...
How to download the file after a successfully ajax call? What is the next step?
I already did my research and I found nothing relevant and/or helpful.
Thanks in advance.
Upvotes: 1
Views: 12305
Reputation: 1
It worked for me, perfectly.
jQuery(document).on( 'click', '.btn_generate_product', function(e) {
var product_id = jQuery(this).data('product_id');
jQuery.ajax({
url : "ajaxurl",
type: 'POST',
data: { product_id },
success: function(data){
/*
* Make CSV downloadable
*/
var downloadLink = document.createElement("a");
var fileData = ['\ufeff'+data];
var blobObject = new Blob(fileData,{
type: "text/csv;charset=utf-8;"
});
var url = URL.createObjectURL(blobObject);
downloadLink.href = url;
downloadLink.download = "products.csv";
/*
* Actually download CSV
*/
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
});
});
Upvotes: 0
Reputation: 2725
Return the url of the .csv file in your ajax call. Then in your success function put:
location.href = url;
Just like all file types that are not naturally handled by the browser this will cause the browser to download the file.
Upvotes: 2
Reputation: 1
Try creating a
element with href
attribute set to data URI
of file using URL.createObjectURL
, Blob
; download
attribute to set file name for "Save file" dialog
success: function (data) {
var resp = data.response;
var a = $("<a />", {
href: "data:text/csv,"
+ URL.createObjectURL(new Blob([resp], {
type:"text/csv"
})),
"download":"filename.csv"
});
$("body").append(a);
a[0].click();
}
Upvotes: 1