DOMPDF not downloading file when using AJAX

2019-08-21 16:50发布

I'm trying to work with the BarryVdh/DOMPDF code in my Laravel project. I made a page with a print button, with

<a href="/print-facturen" class="btn btn-default printbtn">Print</a>

This is calling the controller function :

   public function printFacturen(Request $request) {

        $facturen = Factuur::all();
        view()->share('facturen', $facturen);

        $pdf = PDF::loadView('pdf.facturen');
        return $pdf->download('invoice.pdf');
    }

This is successfully downloading the PDF file.

My route is :

Route::get('/print-facturen', 'PrintController@printFacturen')->name('print_overzicht_facturen');

But, I need the content of a radio button to fill my PDF instead. So I change my a href to

<a href="#" class="btn btn-default printbtn">Print</a>

I add a jQuery function :

   $(".printbtn").click(function(e)
    {
        var option = $("input[name='factuur_selectie']:checked").val();

        $.ajax({
            type: 'POST',
            url: 'print-facturen',
            data: {"optionID": option}
        })
    });

And my controller is changed to

   public function printFacturen(Request $request) {

        $option = $request->get('optionID');

        $facturen = Factuur::all();
        $searchFacturen = new \Illuminate\Database\Eloquent\Collection();

        foreach ($facturen as $factuur) {
            if ($option == 1) {
                $searchFacturen->add($factuur);
            }
            else if ($option == 2) {
                if ($factuur->voldaan == true) {
                    $searchFacturen->add($factuur);
                }
            }
            else if ($option == 3) {
                if ($factuur->voldaan == false) {
                    $searchFacturen->add($factuur);
                }
            }
        }
        view()->share('facturen', $searchFacturen);

        $pdf = PDF::loadView('pdf.facturen');
        return $pdf->download('invoice.pdf');
    }

I can see my optionID successfully, but the PDF file is NOT being downloaded anymore ... :-(

As I got a POST error, I added this route :

Route::post('/print-facturen', 'PrintController@printFacturen')->name('print_overzicht_facturen');

When inspecting the network, I see this :

SORRY, I'm not allowed yet to post pictures here :-( (https://user-images.githubusercontent.com/5870500/32404394-3555952c-c14f-11e7-82c3-2d000d1a2661.png)

What am I doing wrong ?

Best regards,

Davy

1条回答
Summer. ? 凉城
2楼-- · 2019-08-21 17:44

You need to set proper http response headers:

header('Content-Type: application/octet-stream; charset=utf-8');
header('Content-Disposition: attachment; filename="'.$filename.'"');

Other simple option to do it will be to dynamic modify link on radio click to get link like: example.org/download?radio=1

查看更多
登录 后发表回答