Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export CSV using Laravel via Ajax

I have a export csv function, it worked fine with laravel. But now I want to call export function via ajax and use method post, but I there is no respone. I can send a variable from laravel controller to response, but can not send a file download.

Here is my code :

route.php

    Route::get('/title/show', 'TitleController@show');
    Route::post('/title/show', 'TitleController@exportFromDB');

show.blade.php

<script>
$(document).ready(function () {
    $('#exportFromDB').click(function () {
        $.ajax({
            url: "",
            type: "post",
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            data: {},
            success: function (response) {
                var a = document.createElement("a");
                a.href = response.file;
                a.download = response.name;
            }
        })
    })
})

TitleController.php:

    $dataExport['Oversea'] = $dataOversea;
    $this->titleRepository->export('csv', $properties, $dataExport);

TitleRepository.php

public function export($type, $properties, $data)
{
    if (in_array($type, self::EXPORT_TYPE)) {
        try {
            return Excel::create($properties['_title'], function ($excel) use ($data, $properties) {

                $excel->setTitle($properties['_title']);
                $excel->setCreator($properties['_creator'])
                    ->setCompany($properties['_company']);
                $excel->setDescription($properties['_description']);

                $excel->sheet('Sheet', function ($sheet) use ($data) {
                    foreach ($data as $item) {
                        $sheet->fromArray($item);
                    }
                });
            })->export($type);
        } catch (Exception $error) {
            throw $error;
        }
    }
}

How can I fix them ? Thank !

like image 519
Manh Nguyen Avatar asked Mar 09 '23 08:03

Manh Nguyen


1 Answers

Try this -

  1. Don't write the code for export in your controller method, instead just save the excel file in your public folder.

  2. Your controller method should return the filename.

  3. On your ajax success do this -

location.href = path/to/file/property_title.xls

So replace your this line

->export($type); 

with

->store($type, 'public/reports/', true);
like image 55
Mr.Gandhi Avatar answered Mar 16 '23 07:03

Mr.Gandhi