Question:: I am developing a plugin. This plugins creates a custom table in WP database. How can I export the data from this table using Ajax?
Where I am?: I have created the hook and the handler. I can actually grab the data. Please see my code below.
add_action ( 'wp_ajax_nopriv_exportcsv', 'exprot_to_csv' );
add_action ( 'wp_ajax_exportcsv', 'exprot_to_csv' );
<script type="text/javascript">
jQuery("#export-csv").on("click",function(e){
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: {"action":"exportcsv"},
success: function(response){alert(response);}
})
});</script>
function exprot_to_csv(){
global $wpdb;
$table_prefix = $wpdb->prefix;
$table = $table_prefix.'my_custom_table';
$result = $wpdb->get_results("SELECT * FROM ".$table."");
foreach ($result as $row) {
$output .="n";
$output .='"'.$row->post_id.'",';
}
$output .="n";
$file = "custom_table";
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
echo $output;
exit;
}
In the alert box, I am getting comma separated post IDs as expected. But I am not sure how to move on from here. I mean how to handle this response and prompt the user to save/download the file.
Any help?
You are close…! I ran into same problem, tried a similar solution.
Check this question out:
Download file through an ajax call php
And THIS specific answer:
https://stackoverflow.com/a/11452917
Make sure to look at Dario’s answer
Summary –
Serve up your file with a File Transfer
This works in WordPress. Use Admin-Ajax.
Cheers
Hopefully this will solve your problem.
In jQuery:
Action ajax:
Please remove all headers