Reputation: 1020
I'm trying to implement excel export function for my table. I'm sending form data with ajax and php script creates file with this data and then nothing. I want ajax return the file created with php. Here is my code.
$('body').on('click', '#excel', function() {
var veri = $('form[method="get"]').serializeArray();
veri['action'] = 'userexcel';
jQuery.ajax({
type: "POST",
url: <?php echo '"' . admin_url( 'admin-ajax.php' ) . '"';?>,
data: veri,
success: function(data){
alert(data);
}
});
return false;
});
And my php function
function exportExcel($filename='ExportExcel',$columns=array(),$data=array(),$replaceDotCol=array()){
header('Content-Encoding: UTF-8');
header('Content-Type: text/plain; charset=utf-8');
header("Content-disposition: attachment; filename=".$filename.".xls");
echo "\xEF\xBB\xBF"; // UTF-8 BOM
$say=count($columns);
echo '<table border="1"><tr>';
foreach($columns as $v){
echo '<th style="background-color:#FFA500">'.trim($v).'</th>';
}
echo '</tr>';
foreach($data as $val){
echo '<tr>';
for($i=0; $i < $say; $i++){
if(in_array($i,$replaceDotCol)){
echo '<td>'.str_replace('.',',',$val[$i]).'</td>';
}else{
echo '<td>'.$val[$i].'</td>';
}
}
echo '</tr>';
}
}
Upvotes: 0
Views: 372
Reputation: 37298
The excel generation code works just fine, however, if you want to force the browser to download that file, you have two options.
Create a local xls file
You'll have to actually save that file somewhere on the server, then return the link to it and then initiate the download by changing the window.location.href = "<url_of_xls_file>"
after the successful AJAX call.
Make the form post directly to the wordress AJAX call
Now, if you don't want to create an xls file on the server, then you'll have to get rid of the ajax approach, change your form action
attribute to admin_url( 'admin-ajax.php' )
and manually add the <input type="hidden" name="action" value="userexcel">
wordpress action inside your form.
You'll have the browser to popup the download dialog with both of these methods.
Upvotes: 1