Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

400
Views
How to download CSV file on backend after AJAX request

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!