2

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.

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?

Awais Umar
  • 2,027
  • 3
  • 27
  • 46
  • Can you check with your FTP to see if in the root of the wp folder you have a `.csv` file? – dingo_d Mar 22 '16 at 11:17
  • Just checked. Its not in the server. – Awais Umar Mar 22 '16 at 11:19
  • 1
    Possible duplicate of [Download CSV file using "AJAX"](http://stackoverflow.com/questions/3346072/download-csv-file-using-ajax) – dingo_d Mar 22 '16 at 11:21
  • @dingo_d, I did have checked that. But he is getting a file created in the server but can't show the download dialogue box. While my file isn't actually being created. – Awais Umar Mar 22 '16 at 11:29
  • How not? Just put the contents of your function `exprot_to_csv()` to `exprot_to_csv.php`, and call that file on click ;) Should be working :) – dingo_d Mar 22 '16 at 11:30
  • Hahaha. I got what you meant :-) So there is no apparent way that I can get this directly via a function rather than a file? – Awais Umar Mar 22 '16 at 11:32
  • Well I haven't try. I know that I always got the `headers already sent...` error when I tried something similar to that. You can see the output in the Networks tab in the inspector when you trigger the ajax call, see if there is errors beside the returned ID's. – dingo_d Mar 22 '16 at 11:37
  • Apparently I am lucky here. I do not see any errors :-) – Awais Umar Mar 22 '16 at 11:46
  • @dingo_d, so I inserted the code into a separate export.php and when I call that file on click using window.location.href, wordpress gives me error "Trying to get property of non-object" – Awais Umar Mar 22 '16 at 12:03
  • You can't return a file via ajax. Make a post request to your method returning header("Content-Type: text/csv"); or header("Content-Disposition: attachment") if you'd like to save the file first – Vitor Rigoni Mar 22 '16 at 12:15
  • Maybe this answer can point you a way: http://stackoverflow.com/a/33396810/5970334 – Felipe Elia Mar 22 '16 at 13:22
  • You have to use action: **exprot_to_csv** , not **exportcsv**. But seem ajax can't download a file. I also have same problem. Anyone help me an answer? – huykon225 Dec 12 '17 at 04:41

2 Answers2

2

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

Christian Žagarskas
  • 1,068
  • 10
  • 20
0

Hopefully this will solve your problem.

In jQuery:

 window.location = response->in success

Action ajax:

Please remove all headers

echo admin_url($filename);
die;
BSMP
  • 4,596
  • 8
  • 33
  • 44