简体   繁体   中英

wordpress ajax export to csv file download without extension

In wordpress I want to generate csv file using ajax. So basically when user will click on button it will make an ajax call and in ajax php file it will make the csv and download it to the user system. So for that I have done my code like this

My markup is like this

<button type="button" class="btn export-csv" data-proj-id="1">Export CSV</button>

js code is like this

$('body').on('click', 'button.export-csv', function() {
    var proj_id = $(this).attr('data-proj-id');
    $.ajax({
        type:"POST",
        url:trans.ajaxUrl,
        data:'proj_id='+proj_id+'&action=export_client_price_csv',
        success: function (data) {
            var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(data);
      location.href = uri;
    }
    }); 
});

My php code looks like this

function export_client_price_csv() {
    global $wpdb;
    $proj_id = $_POST['proj_id'];
    $user_id = get_current_user_id();
    $site_id = get_current_blog_id();
    if( !empty($proj_id) ) {
        $get_prices_data = $wpdb->get_results("SELECT * FROM `fl_client_price` WHERE `user_id` = ".$user_id." AND
        `project_id` = ".$proj_id." AND `site_id` = ".$site_id." AND `client_status` LIKE '%invoiced%' ");

        $data_array = array();
        if( count($get_prices_data) > 0 ) {
            foreach( $get_prices_data as $data ) {
                $array = get_object_vars($data);
                array_push($data_array, $array);
                convert_to_csv($data_array, 'report.csv', ',');
            }
        }
    }
    exit;
}
add_action( 'wp_ajax_export_client_price_csv', 'export_client_price_csv' );

function convert_to_csv($input_array, $output_file_name, $delimiter)
{
    /** open raw memory as file, no need for temp files, be careful not to run out of memory thought */
    $f = fopen('php://memory', 'w');
    /** loop through array  */
    foreach ($input_array as $line) {
        /** default php csv handler **/
        fputcsv($f, $line, $delimiter);
    }
    /** rewrind the "file" with the csv lines **/
    fseek($f, 0);
    /** modify header to be downloadable csv file **/
    header('Content-Type: text/html; charset=UTF-8');
    //header('Content-Type: application/csv');
    header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
    /** Send file to browser for download */
    fpassthru($f);
}

When I am doing click on the button it's doing download the file but without the extension .csv . I don't know what's happening here. Can someone tell me how to solve this issue?

Looks like there is no way of specifying filename.extension using location.href or window.location.href .

It is possible to specify filename.extension if you instead emulate an anchor click:

var csvdata = "Hello World"; //  only for test
var byteNumbers = new Uint8Array(csvdata.length);

for (var i = 0; i < csvdata.length; i++)
{
    byteNumbers[i] = csvdata.charCodeAt(i);
}
var blob = new Blob([byteNumbers], {type: "text/csv"});

// Construct the uri
var uri = URL.createObjectURL(blob);

// Construct the <a> element
var link = document.createElement("a");
link.download = 'myfile.csv';
link.href = uri;

document.body.appendChild(link);
link.click();

// Cleanup the DOM
document.body.removeChild(link);
delete link;

See here: how to specify csv file name for downloading in window.location.href

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM