Link to download an Excel spreadsheet

My server is capable of generating excel files dynamically, and I am utilizing AJAX to download these dynamic excel files. Upon successful completion in the callback function, I receive the data for the excel file.

    $.ajax({
            url: exporting.action,
            headers: { "Authorization": "Basic " + btoa("key : " + key) },
            type: "post",
            success: function(res){
                 //res contains the excel file that requires downloading
                 //I know we can download images using anchor tags, but unsure about downloading excel files
            },
            data: { 'Model': JSON.stringify(modelClone) }
        });

I would appreciate suggestions on how to incorporate this data into the href attribute of an anchor tag for downloading purposes?

Note:

1) The usage of AJAX is essential for header authorization

Answer №1

To enhance your request, include the following: dataType: "binary" and responseType: "arraybuffer" properties.

$.ajax({
    url: exporting.action,
    headers: { "Authorization": "Basic " + btoa("key : " + key) },
    type: "post",
    responseType: "arraybuffer",
    dataType: "binary",
    success: function(res){
        //res refers to the excel file that requires downloading
        //While we can download images using anchor tags, file downloads might differ
    },
    data: { 'Model': JSON.stringify(modelClone) }
});

This will provide you with an array buffer that can be easily downloaded via Blob and object URL.

var blob = new Blob([arraybuffer], {type: "application/vnd.ms-excel"});
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);

In your specific scenario:

$.ajax({
    url: exporting.action,
    headers: { "Authorization": "Basic " + btoa("key : " + key) },
    type: "post",
    success: function(res){
        var blob = new Blob([res], {type: "application/vnd.ms-excel"});
        var objectUrl = URL.createObjectURL(blob);
        window.open(objectUrl);
    },
    data: { 'Model': JSON.stringify(modelClone) }
});

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

Enhance the progression bar using JavaScript

Is there a way to dynamically update a progress bar in HTML while a function is running? function fillProgressBar() { var totalIterations = 100; for (var i = 1; i <= totalIterations; i++) { //perform calculations progressBarWidth = (i/to ...

Error: Trying to assign a value to a null property

I am facing an issue while trying to dynamically create "iframe's textarea" and insert the value of a variable. Unfortunately, I keep encountering an error. Any suggestions on how to resolve this problem? P.S: Using Google Chrome as the browser ...

Setting up a local development environment for AngularJS

I have been using the boilerplate https://github.com/node90/angular-starter as a foundation for my projects. However, I've noticed that the repository utilizes gulp to consolidate the js files in the 'app' folder into the 'public/js&apo ...

Issue with AJAX MVC HTML: jQuery value is not blocking API call

Upon clicking a button, I am triggering a web API call using AJAX. My form is utilizing JqueryVal for form validations based on my viewmodel data annotations. The issue I am facing is that when I click the "Listo" button in my form, it executes the API ca ...

I'm having trouble getting FlowType.js to function properly

I have added the following code just before the closing </body> tag, but unfortunately, it seems like the type is not changing as expected. I am struggling to identify what mistake I might be making. Check out FlowType.JS on GitHub View the code on ...

Implementing Ajax for displaying panels in Apache Wicket framework

I am currently learning the Wicket framework and I encountered an issue while working with AJAX. I attempted to display a panel with the selected radio button's company name, but unfortunately, I'm experiencing an error. I have included all the r ...

The functionality of iScroll becomes unresponsive once I implement Ajax to load the list

I have successfully implemented an iScroll list that works perfectly when coded directly into the HTML. However, when I attempt to use jQuery-Ajax to dynamically load the same list, it remains stuck at the top and refuses to scroll down to the bottom. $( ...

Retrieve the following object in an array of objects using a specific property value in Javascript

I am working with an array of objects structured like this: orders: [ 0: { order_id: 234, text: 'foo' }, 1: { order_id: 567, text: 'bar' } ] Suppose I have the ID 234 and I want to find the next object in the a ...

My JavaScript code is being executed before Chrome Auto-fill

I have successfully created form input elements in Chrome that display a floating label when focused. However, I am encountering an issue when the browser autofills the username and password fields with yellow prefilled text. The JavaScript for the float ...

Pass the returned variable value from a request.get call to another function in NodeJS Express

I have a situation where I am calling a function that makes a request to get some JSON data and then fills in the variables from my router.get method. The issue I am facing is that the variables are getting their value inside the callFunc function, but wh ...

What is the best way to extract a particular key value from a JSON object?

I am completely new to the world of APIs and just starting out with JavaScript. My goal is to retrieve the status of a server from a server hosting panel using an API. In order to achieve this, I need to log in by making a request to /API/Core/Login, extra ...

The value of req.files consistently shows as undefined

My issue is with req.files consistently returning undefined. Despite attempting connect-multiparty, body-parser, and express-fileupload, I can't seem to make it work with express-fileupload instead of multer. Can anyone help me troubleshoot this probl ...

Encountering an undefined json array when making an AJAX request

There have been numerous questions on this topic, but none of the specific solutions seemed to apply to my situation. So, I apologize if this is a duplicate query. I am currently working on fetching data from an SQL database using a PHP file that passes t ...

Reposition div when clicked

I have encountered a challenge where I am unable to perform a small task. My goal is to have the position of "div1" change upon clicking on "div2", taking into account that "div2" is nested inside "div1". Additionally, when clicking on "div2" again, "div1" ...

Prevent discrepancies between the outcome on the server and the client side

My website utilizes a combination of PHP and JavaScript for processing results - some server-side, some client-side. Solely relying on JavaScript can cause issues with search engine crawling, while using only PHP may not provide real-time responses accura ...

Efficient Ways to pass information to an Object within a nested function

const http = require('https'); exports.ip = async (req, res) => { const ip = req.body.ip; const ip_list = ip.trim().split(' '); const count = ip_list.length; var execution_count = 0; var success = {}; // **Creati ...

Is there a way to verify that all CSS files have been successfully downloaded before injecting HTML with JavaScript?

I am looking to dynamically inject HTML content and CSS URLs using JavaScript. I have more than 3 CSS files that need to be downloaded before the content can be displayed on the page. Is there a way to check if the aforementioned CSS files have finished ...

trigger a label click when a button is clicked

I am in need of assistance with simulating a label click when a button is clicked. I attempted to make the label the same size as the button so that when the button is clicked, it would check my checkbox. I then tried using JavaScript to simulate the label ...

Combining multiple storageStates in a playwright context for efficient loading

I am trying to load multiple storageStates into a single context in playwright, but I am facing some issues. When using the following code: const context = await browser.newContext({ storageState: "telegram.json",storageState: "google. ...

Using perl ajax to modify a table

In my current Perl script, I am working on a functionality where I retrieve data from an xls file and display it as input text on a webpage. The objective is that when a user selects the edit option from a menu, the entire table fetched from the xls file w ...