Trying to generate CSV from wordpress custom table


Trying to generate CSV from wordpress custom table



I am trying to export data from a wordpress custom table. I have two jquery UI datepicker which represents the start and end date. I'm sending the date filed value via wp ajax with button click. If I pass date values static then the csv generates, but with the value stored inside variables $sdate and $edate does not work. If I pass store static value inside those variables that also works. I can see that ajax function is submitting date field value. Not sure what's wrong with the code.



Here is my function:


add_action( 'wp_ajax_sharepricedownload', 'sharepricedownload' );
add_action( 'wp_ajax_nopriv_sharepricedownload', 'sharepricedownload' );
function sharepricedownload() {
global $wpdb;
$sdate=$_REQUEST['sdate'];
$edate=$_REQUEST['edate'];
// $sdate='2018-06-19';
// $edate='2018-06-19';
$file = 'shareprice';
$results = $wpdb->get_results("SELECT TICKER,DATE,OPEN FROM share_prices WHERE DATE BETWEEN '$sdate' AND '$edate' ", 'ARRAY_A');
//$results = $wpdb->get_results("SELECT TICKER,DATE,OPEN FROM share_prices WHERE DATE BETWEEN '2018-06-19' AND '2018-06-19' ", 'ARRAY_A');
if (empty($results)) {
return;
}
$head=array('TICKER','DATE','OPEN');
$fp= fopen('php://output', 'w');
fputcsv($fp,$head);
//fputcsv($fp,$results);
foreach ($results as $row) {
fputcsv($fp, $row);
//echo $row;
}
$csv_output .= "n";
$filename = $file;
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit();
}



My jquery:


$('#sbts').click(function(){
var sdate = $("#datepicker").val();
var edate = $("#datepicker2").val();
var data= { action: 'sharepricedownload', 'sdate' :sdate, 'edate':edate};
jQuery.post(ajaxurl, data,function(response) {
window.open('<?php echo home_url('/'); ?>wp-admin/admin-ajax.php?action=sharepricedownload', 'myNewPage');
});
});









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API