0

What im doing:

The data i want to print out in the csv file is sent to a PHP/laravel backend from a JS/vue frontend

The data is being sent via an axios.post request to a laravel controller function

Whats wrong

The csv file does not download when the function is hit (all data is received on backend)

Whats happening

Instead of downloading a CSV file, the data just get returned from the function

Here is me sending data to the backend

printReport() {
        axios.post('/admin/assignments/printReportData', {
            'assignments': this.reportAssignments,
            'users': this.reportUsers
        })
}

The backend function being hit

 public function printReportData(Request $request)
{

    $assignments = $request->assignments;
    $users = $request->users;

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=sales-by-item-per-customer' . date('YmdHi') . '.csv');
    $output = fopen("php://output", "w");
    fputs($output, $bom = (chr(0xEF) . chr(0xBB) . chr(0xBF)));
    

    foreach ($assignments as $assignment) {
        fputcsv($output, [$assignment['name']]);
        foreach ($users as $user) {
            //get all user ids in specific assignment responses array
            $userIdArray = array_column($assignment['response'], 'user_id');
            //get array of current assignment response
            if (in_array($user['id'], $userIdArray)) {
                fputcsv($output, [$assignment['name'], $user['name'], 'Completed']);
            } else {
                fputcsv($output, [$assignment['name'], $user['name'], 'Not Complete']);
            }
        }
    }

    fclose($output);
    

}

After hitting the above function, the data is looped out and returned - i can see that via the dev tools

The CSV never downloads

What ive tried

I tried to force the download different ways:

after fclose($output); i have tried exit(); and die(); but nothing has forced the download to commence

The backend code in the function above worked on a full page load, just not when i try do it via axios

  • The script is making the request, not the end user. So it wouldn't make sense to prompt the user to download something. There are a few workarounds in the duplicate questions such as hidden iframes and data URI links. – miken32 Feb 01 '22 at 23:33

0 Answers0