0

I have this function which generates a CSV and stores on the server (this works fine) however it is not pushing to the browser for the user to download, can anyone see why?

It is also putting the data into multiple sections like;

invoice details

customer details

invoice items

I would prefer if this put all the data onto 1 line rather than 3 sections but not sure how to do this.

Function:

// download invoice csv sheet
if ($action == 'download_csv'){

    header("Content-type: text/csv"); 

    // Connect to the database
    $mysqli = new mysqli(DATABASE_HOST, DATABASE_USER, DATABASE_PASS, DATABASE_NAME);

    // output any connection error
    if ($mysqli->connect_error) {
        die('Error : ('.$mysqli->connect_errno .') '. $mysqli->connect_error);
    }

    $tables = array('invoices', 'customers', 'invoice_items'); // array of tables need to 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 a file in write mode
    chmod($file_path, 0777);    // set the file permission

    // loop for tables
    foreach($tables as $table) {
        $table_column = array();
        $query_table_columns = "SHOW COLUMNS FROM $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 as CSV and write to file pointer
        fputcsv($file, $table_column, ",", '"');

        $query_table_columns_data = "SELECT * FROM $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 as $data) {
                    $table_column_data[] = $data;
                }

                // Format array as CSV and write to 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 a saved file to 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 successfully generated and also been stored in the 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 a problem, please try again.");
                $("#response").removeClass("alert-success").addClass("alert-warning").fadeIn();
                $("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
            } 
        });

    }
halfer
  • 19,824
  • 17
  • 99
  • 186
James
  • 1,668
  • 19
  • 50
  • what kind of error are you seeing? – Eli Y May 12 '15 at 09:23
  • 1
    What Elibyy is asking. What is not working? Does the download not start? Are you getting errors in your error log? Is a different page served? I'm actually expecting a `cannot modify header information - headers already sent`. – Erik S May 12 '15 at 09:26
  • I look in console on response.php and just see the data returned and error comes back on page that opps,. something went wrong – James May 12 '15 at 09:30
  • Updated with JS so its coming back as error – James May 12 '15 at 09:31
  • just a note you specify in jQuery.ajax that you intend to receive json but your sending csv content – Eli Y May 12 '15 at 09:32
  • Im doing POST so can send action to PHP to run the function – James May 12 '15 at 09:35
  • yeah i understood that but you cannot specify dataType: 'json' and receive csv data, that will cause jQuery to perform calling the error callback since it couldn't decode it as JSON http://api.jquery.com/jquery.ajax/ – Eli Y May 12 '15 at 09:36
  • Oh ok, im pretty new to this so a little confused, what do i need to do so it asks to download / save? – James May 12 '15 at 09:41
  • check out this answer http://stackoverflow.com/a/9970672/925083 – Eli Y May 12 '15 at 09:45

0 Answers0