jquery - PHP to download generated CSV not pushing to the browser for download -
so have function generates csv , stores on server (this works fine) not pushing browser user download, can see why?
it putting data multiple sections like;
invoice details
customer details
invoice items
i prefer if put data onto 1 line rather 3 sections not sure how this, can me well.
thanks in advance guys! have hour live if me great!
function:
// download invoice csv sheet if ($action == 'download_csv'){ header("content-type: text/csv"); // connect database $mysqli = new mysqli(database_host, database_user, database_pass, database_name); // output connection error if ($mysqli->connect_error) { die('error : ('.$mysqli->connect_errno .') '. $mysqli->connect_error); } $tables = array('invoices', 'customers', 'invoice_items'); // array of tables need export $file_name = 'invoice-export-'.date('d-m-y').'.csv'; // file name $file_path = 'downloads/'.$file_name; // file path $file = fopen($file_path, "w"); // open file in write mode chmod($file_path, 0777); // set file permission // loop tables foreach($tables $table) { $table_column = array(); $query_table_columns = "show columns $table"; // fetch table field names if ($result_column = mysqli_query($mysqli, $query_table_columns)) { while ($column = $result_column->fetch_row()) { $table_column[] = $column[0]; } } // format array csv , write file pointer fputcsv($file, $table_column, ",", '"'); $query_table_columns_data = "select * $table"; if ($result_column_data = mysqli_query($mysqli, $query_table_columns_data)) { // fetch table fields data while ($column_data = $result_column_data->fetch_row()) { $table_column_data = array(); foreach($column_data $data) { $table_column_data[] = $data; } // format array csv , write file pointer fputcsv($file, $table_column_data, ",", '"'); } } } // close file pointer fclose($file); // ask either save or open header("pragma: public"); header("expires: 0"); header("content-type: application/octet-stream"); header("content-disposition: attachment; filename='{$file_name}';" ); header("content-transfer-encoding: binary"); // open saved file read data $fhandle = fopen($file_path, 'r'); fpassthru($fhandle); fclose($fhandle); $mysqli->close(); die; }
js
function downloadcsv(action) { jquery.ajax({ url: 'response.php', type: 'post', data: action, datatype: 'json', success: function(data){ $("#response .message").html("<strong>success</strong>: csv has been generated , been stored in downloads/ directory."); $("#response").removeclass("alert-warning").addclass("alert-success").fadein(); $("html, body").animate({ scrolltop: $('#response').offset().top }, 1000); }, error: function(data){ $("#response .message").html("<strong>error</strong>: oppps there has been problem, please try again."); $("#response").removeclass("alert-success").addclass("alert-warning").fadein(); $("html, body").animate({ scrolltop: $('#response').offset().top }, 1000); } }); }
Comments
Post a Comment