Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate and download CSV file with php and ajax

I have a php page that creates a CSV file that is then downloaded by the browser automatically. Here is a version with sample data - it works great.

<?php

$cars = array(
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=csvfile.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('Car', 'Year', 'Miles' ));

//Loop through the array and add to the csv
foreach ($cars as $row) {
    fputcsv($output, $row);
}

?>

I would like to be able to run this from another page using ajax so that a user can generate/download a csv without leaving the main page. This is the JavaScript I am using on the main page. In my real page I am using the data coming via ajax.

$('button[name="exportCSVButton"]').on('click', function() {
    console.log('click');
    $.ajax({
        url: 'exportCSV.php',
        type: 'post',
        dataType: 'html',
        data: {

            Year: $('input[name="exportYear"]').val()
        },
        success: function(data) {
            var result = data
            console.log(result);


        }
    });
});

When I click the button to trigger the script, it runs, but instead of saving/download to csv it prints the entire thing to console. Is there any way to accomplish what I want? Without actually saving the file to the server and reopening.

like image 294
blackandorangecat Avatar asked Dec 29 '17 00:12

blackandorangecat


People also ask

How do I download a csv file from Ajax in PHP?

You can simply do server side working with php then call it by using ajax. $dataArr=array(); //whatever array you want to get as csv file...

How do I download a csv file from PHP?

PHP fputcsv() csv file with the reference of the given file pointer. The syntax of this function is, fputcsv($file_pointer, $input_array, $delimiter = ',', $enclosure = '"'); In this code, we are creating the file pointer by opening PHP output stream.


1 Answers

I have done csv file download via ajax

PHP Code

    <?php
         function outputCsv( $assocDataArray ) {

            if ( !empty( $assocDataArray ) ):

                $fp = fopen( 'php://output', 'w' );
                fputcsv( $fp, array_keys( reset($assocDataArray) ) );

                foreach ( $assocDataArray AS $values ):
                    fputcsv( $fp, $values );
                endforeach;

                fclose( $fp );
            endif;

            exit();
        }

        function generateCsv(){
            $res_prods = $wpdb->get_results( "SELECT * FROM `{$wpdb->prefix}products` ", OBJECT );

            $products= [];
            foreach ($res_prods as $key => $product) :
                $product_id = $product->ID;

                $products[$product_id]['product_id'] = $product_id;
                $products[$product_id]['name'] = $product->name;
            endforeach;

            return outputCsv( $products);
      }

jQuery AJAX

jQuery(document).on( 'click', '.btn_generate_product', function(e) {

    var product_id = jQuery(this).data('product_id');

    jQuery.ajax({
        url : "ajaxurl", 
        type: 'POST',
        data: { product_id },
        success: function(data){

              /*
               * Make CSV downloadable
               */
              var downloadLink = document.createElement("a");
              var fileData = ['\ufeff'+data];

              var blobObject = new Blob(fileData,{
                 type: "text/csv;charset=utf-8;"
               });

              var url = URL.createObjectURL(blobObject);
              downloadLink.href = url;
              downloadLink.download = "products.csv";

              /*
               * Actually download CSV
               */
              document.body.appendChild(downloadLink);
              downloadLink.click();
              document.body.removeChild(downloadLink);

        }
    });
});
like image 156
Mayank Dudakiya Avatar answered Sep 19 '22 10:09

Mayank Dudakiya