0

I want to export CSV file in Laravel but it returns only text.

$(document).on("click","#csvIcon",function(){
$('#mask').css('display','block');
var fId=$(this).attr('data-formId');
$.get('/clientarea/form/responses/csv/export',
    {'formId':fId},
    function (data,status,xhr) {
        $('#mask').css('display','none');
     }
   )

});

route:

  Route::get('/clientarea/form/responses/csv/export',[ResponsesController::class,'exportCsv']);

My controller: In the controller I have to array $data and $questions that fetched from database to create my csv content.

public function exportCsv(Rrequest $request)
  ...
  $data=['a','b','c','d'];
  $questions=['s1','s2','s3','s4'];
                   function cleanData(&$str)
             {
               if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
                $str = "'$str";
            }
            if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
        }
        $fileName = "form_data_" . date('Ymd') . ".csv";
        $headers = array(
            "Content-type"        => "text/csv",
            "Content-Disposition" => "attachment; filename=$fileName",
            "Pragma"              => "no-cache",
            "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
            "Expires"             => "0"
        );
        $callback = function() use($data, $questions) {
            $file = fopen('php://output', 'w');
            array_walk($questions, __NAMESPACE__ . '\cleanData');
            fputcsv($file, $questions,',', '"');
            foreach ($data as $row)
            {
                array_walk($row, __NAMESPACE__ . '\cleanData');
                fputcsv($file, $row,',', '"');
            }

            fclose($file);
        };
        return response()->stream($callback, 200, $headers);
 }

It returns for example:

s1,s2,s3,s4

a,b,c,d

instead of the csv file to download

HamHp
  • 23
  • 8
  • checkout maatwebsite/excel package in laravel – Teekay Jun 04 '21 at 20:03
  • A CSV file is text. What you are returning is CSV data. – miken32 Jun 04 '21 at 22:24
  • I know that CSV is text. it returns text as I mentioned in my question. it should show file save dialog to download the CSV file. – HamHp Jun 04 '21 at 22:40
  • I realized why it is happening , It's because of I'm using AJAX technology then it receive plain text instead of CSV file as response. @miken32 – HamHp Jun 04 '21 at 22:43

1 Answers1

0

It is because of Ajax I'm using to export CSV file . I replaced JavaScript with:

$(document).on("click","#csvIcon",function(){
  let formId=$(this).attr('data-formId');
  window.location.href='/clientarea/form/'+formId+'/responses/csv/export'
});

It works properly.

HamHp
  • 23
  • 8