Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

How to return download response from an AJAX handler.

0
by mjauvin, last modified on September 26th, 2023

It's not possible to return Response::download directly from an AJAX handler.

Instead, you must return a redirect link to a download route pointing to the content you want to make available for download.

e.g. cms page

url = /invoices
layout = default
==
function onStart()
{
    $this['invoices'] = Invoice::all();
}

function onDownload()
{
    $invoiceId = post('id');
    return Redirect::to('/download/invoice/' . $invoiceId);
}
==
<div id="invoices">
  <ul>
  {% for invoice in invoices %}
    <li><a href="#" data-request="onDownload" data-request-data="{id: invoice.id}"></li>
  {% endfor %}
  </ul>
</div>

Create a file called routes.php in your plugin's root folder:

<?php

Route::get('/downloads/invoice/{id}', function ($id) {
    $invoicePath = storage_path('invoices/' . $id);
    return Response::download($invoicePath, 'invoice.pdf');
});

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?