简体   繁体   中英

send ajax request to laravel controller to download a pdf

I have table with a column for checkbox, When a certain button is clicked i send checked checkboxs with ajax request to a controller to download a pdf file after it has been made ,but unfortunately it doesn't fire the download box .i hope you help me out.

My Ajax :

<script>
$(document).ready(function()
{
$(document).on('click', '#minvoice', function(event)
{
    //var alert = confirm('Are You Sure?');
    var checkedValues = $('#chkbx:checked').map(function() {
        return this.value;
    }).get();

    $.post('{{route('payments.multiple_invoices')}}', {'checkboxs' : checkedValues, '_token' : $('input[name=_token]').val() }, function(data){
        console.log(data);
    });

});
});
</script>

My Controller :

public function multiple_invoices(Request $request)
{
    if ($request->isMethod('post')) 
    {   
        //export invoice
        $requestData[] = $request->checkboxs;
        $filenamepdf = public_path().'/export/invoices/multiple_invoices.pdf';
        $data = self::getMulInvoiceData($requestData);
        PDFHelper::export($data, $filenamepdf, true);
        return Response::download($filenamepdf, 'Multiple_invoice_'.date('Y-m-d').'_'. time().'.pdf', []);
    }
}

public static function getMulInvoiceData($requestData)
{
    $payments = UnitPayment::whereIn('id', $requestData)->get();
    return View::make('payments.mulInvoice', compact('payments'));
}

My Views:

<td><input id="chkbx" type="checkbox" value="{{ $payment->id }}" /></td>

MulInovices.blade.php :

@foreach($payments as $payment)
<div align="left" style="text-align: left;"><b>payment : {{$payment->id}}  </b></div>
@endforeach

My Route:

Route::any('payments/multiple_invoices', ['uses' => 'PaymentsController@multiple_invoices','as' => 'payments.multiple_invoices']);

i hope you tell me how to get this to work . thanks

Try changing

return Response::download($filenamepdf, 'Multiple_invoice_'.date('Y-m-d').'_'. time().'.pdf', []);

to

return Response::download($filenamepdf, 'Multiple_invoice_'.date('Y-m-d').'_'. time().'.pdf', ['Content-Type' => 'application/pdf']);

(Difference is code below is added in to third parameter [] of Response::download)

'Content-Type' => 'application/pdf'

If you are using Laravel 5+ you can use code below

response()->($filenamepdf, 'Multiple_invoice_'.date('Y-m-d').'_'. time().'.pdf', ['Content-Type' => 'application/pdf']);

What we did is add headers to recognise response as a pdf file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM