PDA

View Full Version : How do i write a function that talks to a php script generating a csv file?



laiboonh
4 Apr 2014, 1:11 AM
I have a button which on click is suppose to run the function below. Its basically calling a php script which writes out a csv file. I use to use window.open until i find the need to send some parameters to the php script. Hence i use Ajax.request. Is this the correct way? What should i do in the success block? How should i deal with the response?


onButtonClickExcel: function(button, e, options) {
//window.open('php/exportInfoToExcel.php');
var grid = this.getCardsGrid(),
data = Ext.encode(grid.filters.getFilterData());
Ext.getBody().mask();
Ext.Ajax.request({
url: 'php/exportInfoToExcel.php',
async: false,
params: {
filter: data
},
success: function(conn, response, options, eOpts) {
Ext.getBody().unmask();
console.log(response);
},
failure: function(conn, reponse, options, eOpts) {
Pvflash.util.Util.showErrorMsg(conn.responseText);
Ext.getBody().unmask();
}
});
},

scottmartin
4 Apr 2014, 6:00 AM
That should be fine .. you can send your params and use window.open on callback(success)



[code]
Ext.Ajax.request({
url : 'generateReport.php',
params : {
report_name : 'myReport',
report_param : ''
},
success : function (xhr) {
window.open('myReport.xls');
},
failure : function () {
}
});

laiboonh
4 Apr 2014, 6:22 AM
Hi Scott,
thank you for the contribution but i don't understand how this can work.
The success function callback has parameters conn, response, options, eOpts
From which did parameter does 'report.xls' come from?

scottmartin
4 Apr 2014, 6:32 AM
That is handled by the backend .. in this case, I used phpExcel .. and create the XLS and send the header



$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');

// Sending headers to force the user to download the file
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: inline;attachment;filename="'.$reports_array['report_name'].'.xls"');

$objWriter->save('xls/'.$reports_array['report_name'].'.xls');
echo "{success:true}";

scottmartin
4 Apr 2014, 6:35 AM
I updated my first post to return as myReport.xls .. typo

laiboonh
4 Apr 2014, 6:45 AM
I see, so for example my php script can generate header(....filename="foobar.xls")
and on the javascript end i just need to do window.open('foobar.xls');

I will give it a go. Thank you very much.