I have a button which calls an exportCSV function. This function preforms a select statement against my postgres database and returns the results via AJAX request.
How can I get the contents of the response served back through the browser to the client as a .csv file? Currently the code only serves a response back in the browsers console. Any advice would be greatly appreciated. Once the php kicks off there is a smarthandler class which takes care of the database interaction.
exportCSV function
exportCSV: function () {
var me = this;
var message = 'Are you sure you want to generate the CSV?';
var icon = Ext.Msg.QUESTION;
Ext.Msg.show({
title: 'Confirm Execution',
message: message,
buttons: Ext.Msg.YESNO,
icon: icon,
fn: function(btn) {
if(btn === 'yes') {
// TODO: Probably should handle an error here.
Ext.Ajax.request({
url: 'data.php',
async: true,
params: {
action: 'export-csv',
id: me.currentRecord.data.id,
type: 'Carrier'
},
success: function(response,opts) {
var data = Ext.decode(response.responseText);
var csvContent = "data:text/csv;charset=utf-8,";
data.forEach(function(infoArray, index){
dataString = infoArray.join(",");
csvContent += index < data.length ? dataString+ "\n" : dataString;
});
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "carrier_profile.csv");
document.body.appendChild(link); // Required for FF
link.click(); // This will download the data file named "carrier_profile.csv".
}
});
}
}
});
}
PHP
else if($action == 'export-csv') {
// Create an array of filters.
$parsedFilters = array();
// TODO: Sanitize the properties better.
if(isset($_REQUEST['filter'])) {
$filters = json_decode($_REQUEST['filter']);
foreach($filters as $record)
array_push($parsedFilters,array($record->property => $record->value));
}
// Convert a request for a specific ID into a filter.
if(isset($_REQUEST['id']))
array_push($parsedFilters,array('id' => $_REQUEST['id']));
$objectHandler = new SmarterHandler($typeDefinition);
$records = $objectHandler->read($type,$parsedFilters);
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=file.csv');
if(count($records) > 0) {
$record = $records[0];
$headings = array();
foreach($record as $key => $value) {
if(is_scalar($value)) {
$headings[] = $key;
echo $key.",";
}
}
echo "\r\n";
foreach($records as $record) {
foreach($headings as $key) {
echo $record[$key].",";
}
echo "\r\n";
}
}
exit();
}