Export CSV using Laravel via Ajax

Viewed 10191

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 !

4 Answers

I installed the maatwebsite/excel package and was able to do it without writing any javascript. All you need to do is setup a link (or typical form post if you prefer) to an action like so:

public downloadItemsExcel() {
    $items = Item::all();
    Excel::create('items', function($excel) use($items) {
        $excel->sheet('ExportFile', function($sheet) use($items) {
            $sheet->fromArray($items);
        });
    })->export('xls');
}

This works for csv/excel files alike. There is no reload of a page in the browser.

First you have to change POST method to GET.

For ajax you can do it like this:

$(document).ready(function () {
    $('#exportFromDB').click(function () {
      $.get('/title/show, function(data){      
        window.location = '/title/show=' + data;
      });        
    })
})
Related