Downloading Laravel Excel Files via an Ajax Call

Is it possible to generate an Excel file using Laravel with PHPSpreadsheet (PHP lib) and then send the XLSX file to the frontend for download?

JSX Section

axios
.get(
    "/excel/export/dashboardTable", {}
)
.then(resp => {
    //success callback
    if (resp.status == 200) {
        const blob = new Blob([resp.data], { type: "application/vnd.ms-excel" });
        let link = URL.createObjectURL(blob);
        let a = document.createElement("a");
        a.download = "Customers.xlsx";
        a.href = link;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }
})
.catch(error => {
    _.forEach(error.response.data.errors, function (
        value,
        el
    ) {
        toastr.error("Error", value, {
            onHidden: function onHidden() { }
        });
    });
})
.finally(() => { });

Backend Section

$response = response()->streamDownload(function () use ($spreadsheet) {
    $writer = new xlsx($spreadsheet);
    $writer->save('php://output');
}, "Dashboard.xlsx");

$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/vnd.ms-excel');

return $response;

Answer №1

Need a solution: update the responseType to Blob.

axios
.get(
    "/excel/export/dashboardTable", {
    responseType: 'blob' //Change the responseType to blob
}
)
.then(resp => {
    //handling success
    if (resp.status == 200) {
        toastr.success("Success", "Updated successfully!", {
            onHidden: function onHidden() {
                let blob = new Blob([resp.data], { type: "application/vnd.ms-excel" });
                let link = URL.createObjectURL(blob);
                let a = document.createElement("a");
                a.download = "file.xlsx";
                a.href = link;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            }
        });
    }
})
.catch(error => {
    _.forEach(error.response.data.errors, function (
        value,
        el
    ) {
        toastr.error("Error", value, {
            onHidden: function onHidden() { }
        });
    });
})
.finally(() => { });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mysterious source utilizing leafletView for showcasing popups within the Angular Leaflet Directive

I've been attempting to implement a pop-up window on an Angular Leaflet map using Prune Cluster, but I keep running into an error stating that 'leafletView' is an unknown provider. Despite following the examples provided on this page, https: ...

Instructions on how to dynamically update a form field based on the input in another field using conditional statements

I'm seeking advice on how to automatically update a field based on user input without the need for manual saving. For example, if the user types '95' in the input field, the equivalent value displayed should be '1.0' in real-time. ...

Using browserify "require" in console: A step-by-step guide

My Rails project now includes the browserify and pinyin packages, thanks to the browserify-rails installation. To find out more about the pinyin package, check out this link: https://github.com/hotoo/pinyin var pinyin = require("pinyin"); console.log(pin ...

Instructions on keeping a numerical counter at its current value for all site visitors

Recently, I integrated a number counter into my website. However, I am facing an issue where the count resets to zero whenever a new visitor accesses the site. I'd like the count to remain persistent and update based on the previous count. For instanc ...

Search for a result based on a connection, but ensure that the association is not included in the final outcome when using

Basically, I'm trying to search for something in a table using the method include: [{ model, where }], but without actually including the model itself. I have two models, Part and Set, with a one-to-many connection. I am looking for Parts that are re ...

Make sure to give an item a little extra attention by highlighting or making it blink after it has

I have a collection of items that I utilize to construct an unordered list using ng-repeat. When a new item is added, I want it to stand out by blinking or having some kind of effect to grab the user's attention. While it would be easy with jQuery, I ...

Upgrade jQuery visibility and opacity animations to pure JavaScript for a more lightweight solution

Currently I am in the process of removing jQuery from an older website. However, I have encountered a problem with an animation that is currently being used. I have managed to replicate the opacity fade effect, but I am struggling to smoothly transition t ...

Issue encountered while loading JSON data into DynamoDB's local instance

I have successfully set up DynamoDB local and everything is functioning as expected after going through their documentation. I have also tested their example code, which worked flawlessly. The Users table has been created with the name "Users". Below is ...

Display a blade modal upon clicking a Vuejs button

I am working on a Laravel Vue application where I need to display user records using a datatable implemented in Vue. Above the datatable, there is a button that allows users to add new records. When a user clicks on the add button, it should trigger the ...

Submit Form Without Reloading -- and successfully submit it

I'm working on a form submission that triggers AJAX and PHP to load data without the need for page reloading. html/php <form method="POST"> <button type="submit" name="image1"> <button type="submit" name="image2"> <button ...

Trouble Loading TypeScript Class in Cast Situation

I've encountered an issue with my TypeScript model while using it in a cast. The model does not load properly when the application is running, preventing me from accessing any functions within it. Model export class DataIDElement extends HTMLElement ...

Building a multi-page application with ExtJs MVC

I'm new to MVC, especially when it comes to extJs. I want to implement the MVC approach in my project. I came across a tutorial at , which provided an example with only one page. In this example, they used app.js to load extjs views. My question is, w ...

JavaScript code for iframe auto resizing is not functioning properly on Firefox browser

I have implemented a script to automatically resize the height and width of an iframe based on its content. <script language="JavaScript"> function autoResize(id){ var newheight; var newwidth; if(document.getElementById){ newh ...

NextJS React - WebpackError: Cannot access 'window' before initialization

I'm delving into the world of React and recently completed the "Getting Started" tutorial for NextJs (link), successfully setting up a new project. However, when attempting to import third-party plugins like current-devices or smooth-scrollbar, I enc ...

Align numbers vertically inside scrollbar center

I have created a program where you can input a number, and it will count from 0 to the specified number. Currently, the numbers are aligned horizontally up to 12 before starting on a new line. However, I would like the numbers to be arranged vertically fr ...

How can I effectively monitor and track modifications to a document's properties in MongoDB?

I'm wondering how to effectively track the values of a document in MongoDB. This involves a MongoDB Database with a Node and Express backend. For example, let's say there is a document within the Patients collection: { "_id": "4k2lK49938d ...

The metro bundler is facing an unexpected glitch and is stuck in the terminal, failing to load

Recently, I've been using explo-cli to work on a react native project. Everything was running smoothly until today when I encountered an error stating that it couldn't find module './iter-step'. Before this, there was also an issue with ...

I am interested in incorporating the ability to select and scroll the window without needing to interact with the scroll bar by

Imagine a visitor wanting to highlight all the information on a webpage. They choose to start dragging their cursor towards the bottom of the window. How can we enable the webpage to smoothly scroll down as they do this? ...

Is it possible to customize the appearance of the selected item in a select box? Can the selected value be displayed differently from the other options?

My current project involves working with the antd' select box. I have been trying to customize the content inside the Option which usually contains regular text by incorporating some JSX into it. The output currently looks like this: https://i.sstati ...

Utilizing Express and ejs to display a JSON using the "<%" tag

I am facing an issue with the code in my index.ejs file. The current code snippet is as follows: var current_user = <%= user %> In my node.js file, I have the following code: app.get("/", function(req, res){ res.locals.user = req.user res. ...