In my application (Yii) I have a Ajax Submit Button which triggers the generation of an Excel file (using PHPExcel). On success I use a hidden form to submit the file to get it downloaded :
<div class="reporting">
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'mydialog',
'options'=>array(
'title'=>'Warning!',
'autoOpen'=>false, //true,
'modal'=>'true',
'width'=>'auto',
'height'=>'auto',
'open' => 'js:function(event, ui) {
}',
'close' => 'js:function(event, ui) {
$(".ui-dialog:has(#mydialog)").empty().remove();
}',
)
));
?>
<table class="contentheader">
<tr>
<td>
<?php echo CHtml::DropDownList('dropDownId', $lastyear, $yearslist, array('options'=>array($lastyear=>array('selected'=>true)) )); ?>
</td>
</tr>
</table>
<br />
<?php echo CHtml::ajaxSubmitButton('Form Ajax Submit Button',
CHtml::normalizeUrl(array('/planning/xlsAbsences')),
array(
'type'=>'POST',
'beforeSend' => "function(request) { console.log('beforeSend'); }",
'data'=>'js:$("#select-year-form").serialize()+"&year="+$("#dropDownId :selected").text()',
'success' => function(response, status, request){
$("#mydialog").dialog("close");
var disp = request.getResponseHeader("Content-Disposition");
if (disp && disp.search("attachment") != -1) {
var filename = disp.substring(disp.indexOf("filename=") + 10, disp.length-1);
var form = $("<form method=\"POST\" action=\"index.php?r=planning/dl\">");
form.append($("<input type=\"hidden\" name=\"content\" value=\"" + request.responseText + "\">"));
form.append($("<input type=\"hidden\" name=\"filename\" value=\"" + filename + "\">"));
$("body").append(form);
form.submit();
}
}
'complete' => "function(request) { console.log(request); }",
'error' => "function(data) { alert('erro'+data); }",
),
array('name' => 'run', 'class' => 'btn btn-success')
); ?>
<?php $this->endWidget('zii.widgets.jui.CJuiDialog');
echo CHtml::link(Yii::t('app','app.menu.reporting.planning.xlsabsence'), '#', array(
'onclick'=>'$("#mydialog").dialog("open"); return false;',
));
?>
</div>
Problem is that the generated file is not a valid Excel file. I suppose that the content of the Excelfile is in request.responseText. I have seen that the generated file that can't be opened by Excel, is encoded in UTF (without BOM). If I generate the file without Ajax Submit Button the file is ok. But its seems to be encoded in ANSI. I was using Notpad++ to see encoding information. When I convert UTF (without BOM) to ANSI the result is not better.
What am I missing here ?
EDIT : I don't know if my description is not clear enough - the Excel file does not exist. The Excel file content is generated when submitting Ajax Submit Button in a CJuiDialog - for example the user opens dialog and chosses a parameter - this generates an Excel File depending on the parameter selected by the user. As the file does not exist I can't see how to download it. The only solution I found to go through a hidden form.
EDIT2 : I published the whole view code (above)