4

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 4

7

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);
Sign up to request clarification or add additional context in comments.

2 Comments

tks so much, your idea is great, but I still can't return the file name. I change ->export() to ->store() and var_dump($this->titleRepository->export('csv', $properties, $dataExport)) but it return null; Can you show me how to rewrite my controller and repository in detailm please :(
Instead of return Excel::create, assign it to variable. Like this $export = Excel::create and than dd($export). After that if ($export) { return $export['full']; } else { $message = empty($data) ? 'There is no records to export' : "Something went wrong please try againg"; \Session::flash('error', $message); return redirect('client-list'); }
0

I see your ajax url null value

Change it to

url : "{{ action('TitleController@exportFromDB') }}"

After that, response is data you return in controller

success: function (response) {}

1 Comment

I think null url is not problem because I can pass a variable from controller to response by return ("a") and die(); :(
0

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.

Comments

0

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;
      });        
    })
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.