1

Hi everyone I have the code below, but when I click on the link generated a new page is open with 0 display on it. What I'm doing wrong?

function list_reservation_to_csv() {

 global $wpdb;
 $table_name = $wpdb->prefix . 'prenotazione_eventi';
 $file = 'email_csv'; // ?? not defined in original code
 $results = $wpdb->get_results("SELECT * FROM $table_name",ARRAY_A);

 if (empty($results)) {
   return;
 }

 $csv_output = '"'.implode('";"',array_keys($results[0])).'";'."\n";;

 foreach ($results as $row) {
  $csv_output .= '"'.implode('";"',$row).'";'."\n";
 }
 $csv_output .= "\n";

 $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");
 print $csv_output;
 exit;

 }
add_action('wp_ajax_csv_pull','list_reservation_to_csv');

$ajax_url = admin_url('admin-ajax.php?action=csv_pull');

<a href="<?php echo $ajax_url; ?>"><button>Scarica csv</button></a>
3
  • Are you displaying PHP errors? If this is the literal source code, it's bound not to work because PHP and HTML code are intermixed. Turn error reporting on; without it all people can do is guess.
    – Pekka
    Apr 26, 2018 at 12:38
  • nope, no errors. Now I'm thinking... wp_ajax_csv_pull action works only in frontend or also in backend? Apr 26, 2018 at 12:47
  • If the code is literally like it is above, there is bound to be a syntax error on the last line though.
    – Pekka
    Apr 26, 2018 at 12:54

1 Answer 1

0

Try adding a nopriv hook

add_action('wp_ajax_nopriv_csv_pull','list_reservation_to_csv');

This adds the option to run the function without being logged in as a registered user.

3
  • nope, same problem Apr 26, 2018 at 12:28
  • Please edit your answer, and add an explanation: why could that solve the problem?
    – fuxia
    Apr 26, 2018 at 12:49
  • try dumping data early and see what you get. ie: after $results = $wpdb-> ... do a var_dump($results). If that looks ok, move to the next point where you alter the data and so on. Also, try replacing print $csv_output; with print_r($csv_output); or echo $csv_output;
    – Mihai
    Apr 26, 2018 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.