0

I am posting a HTML table data as json to server side using jquery $.post for writing the whole table data to csv file. but this is not outputting csv as downloadable for user.

I want to pop up the csv file (which normally happens when we download a file. you know the SAVE or OPEN box for csv)

Client side code

//selectedData is having the data as json 

$.post('ajax/csv_download.php', { 
    selectedData: JSON.stringify(selectedData) 
}, function(html){  });

Server Side code

   global $fh; 
   $fh = @fopen( 'php://output', 'w' );
   $post_data = json_decode($_POST['selectedData']);
   foreach ($post_data as $arr)
   {
     $val1 = $arr->val1  ;
     $val2 = $arr->val2 ;
     $val3 = $arr->val3 ;
     $val4 = $arr->val4 ;
     $val5 = $arr->val5 ;
      $out = array($val1,$val2,$val3,$val4,$val5);
       fputcsv($fh, $out);
      }
phpgeek
  • 47
  • 6
  • 13
  • What happens when you remove the error-supressor? – Mike B Jun 04 '12 at 15:42
  • sorry i dont understood error-supressor – phpgeek Jun 04 '12 at 15:44
  • i did not tried that but this is not the problem. I am getting the data which should be written to the file at jquery response. – phpgeek Jun 04 '12 at 15:46
  • yes..I am sure about this.but I want to pop up (which normally happens when we download a file. you know the SAVE or OPEN box for csv) – phpgeek Jun 04 '12 at 15:48
  • You should read [this](http://stackoverflow.com/questions/217424/create-a-csv-file-for-a-user-in-php) – jbrtrnd Jun 04 '12 at 15:54
  • @JBRTRND my code is working previusly when i was opening a window.open pop up. it was outputting csv. but now I am posting json . output is right , i checked it. but using jquery with post is causing problem – phpgeek Jun 04 '12 at 16:00
  • So [this](http://stackoverflow.com/questions/3613526/php-file-download-using-post-data-via-jquery-ajax) can maybe help you. – jbrtrnd Jun 04 '12 at 16:04
  • @JBRTRND thanks. I got an idea from there and opened a jquery pop up and then posted a form at that. – phpgeek Jun 04 '12 at 16:24
  • 2
    I taken a different form and put the data into the hidden field. I used Form Target=blank and that will pop up a window for downloading csv file – phpgeek Jun 04 '12 at 16:26

1 Answers1

0

Sounds like you want to write the contents of the CSV file back to the browser after setting the 'Content-Type' to 'text/plain' in php. Depending how the web browser is configured, it will prompt the user to Save/Open the file.

<?php 
  $content="name,age,height,weight,gender"; 
  $file="persons.csv";

  header("Content-Type: text/plain"); 
  header("Content-disposition: attachment; filename=$file"); 
  header("Content-Transfer-Encoding: binary"); 
  header("Pragma: no-cache"); 
  header("Expires: 0");

  echo "$content";
?>
Robert Bolton
  • 667
  • 3
  • 8
  • 22