WordPress – Export table as csv using jQuery/Ajax

Question:: I am developing a plugin. This plugins creates a custom table in WP database. How can I export the data from this table using Ajax?

Where I am?: I have created the hook and the handler. I can actually grab the data. Please see my code below.

Read More
add_action ( 'wp_ajax_nopriv_exportcsv', 'exprot_to_csv' );
add_action ( 'wp_ajax_exportcsv', 'exprot_to_csv' );    

<script type="text/javascript">
 jQuery("#export-csv").on("click",function(e){
        jQuery.ajax({
            type: "POST",
            url: ajaxurl,
            data: {"action":"exportcsv"},
            success: function(response){alert(response);}
            })
        });</script>        


function exprot_to_csv(){

global $wpdb;
$table_prefix = $wpdb->prefix;
$table = $table_prefix.'my_custom_table';

$result = $wpdb->get_results("SELECT * FROM ".$table."");
    foreach ($result as $row) {

        $output .="n";
        $output .='"'.$row->post_id.'",';
        }
        $output .="n";
        $file = "custom_table";
        $filename = $file."_".date("Y-m-d_H-i",time());
        header("Content-type: application/vnd.ms-excel");
        header("Content-disposition: csv" . date("Y-m-d") . ".csv");
        header( "Content-disposition: filename=".$filename.".csv");

        echo $output;
        exit;

}

In the alert box, I am getting comma separated post IDs as expected. But I am not sure how to move on from here. I mean how to handle this response and prompt the user to save/download the file.

Any help?

Related posts

2 comments

  1. You are close…! I ran into same problem, tried a similar solution.

    Check this question out:
    Download file through an ajax call php

    And THIS specific answer:
    https://stackoverflow.com/a/11452917
    Make sure to look at Dario’s answer

    Summary

    1. AJAX is not for streaming downloads.
    2. The solution here is to make an iFrame
    3. Load a PHP file into that iFrame using jQuery
    4. Serve up your file with a File Transfer

      'header('Content-Description: File Transfer');'
      

    This works in WordPress. Use Admin-Ajax.
    Cheers

  2. Hopefully this will solve your problem.

    In jQuery:

     window.location = response->in success
    

    Action ajax:

    Please remove all headers

    echo admin_url($filename);
    die;
    

Comments are closed.