Use AJAX request to download file and handle errors in case the file is not found or cannot be downloaded

Trying to implement an ajax request for downloading a file. Here's the code snippet:

const downloadFile = (element) => { 
    $.ajax({
        url: element.id,
        type: 'GET',  
        success: (result) => {
            window.location=element.id;
        },    
        error: (request,msg,error) => {
            alert(request.responseText);
        }
    })
} 

And the corresponding HTML element: 
'<td>' + `<a id=hiddenAPIRoute href="#" onclick="downloadFile(this)">Download</a>` + '</td>' +

Able to achieve download functionality, but facing double download issue. Prefer using ajax for improved error handling. While aware of html 5's download attribute, want to incorporate an alert in case the file is inaccessible.

Answer №1

To streamline your workflow, consider utilizing the fetch and URL.createObjectURL functions. It's recommended to relocate your API URL to the data-href attribute instead of using the id, which is typically reserved for other purposes:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vite App</title>
</head>

<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a data-href="https://upload.wikimedia.org/wikipedia/commons/b/b6/Image_created_with_a_mobile_phone.png" href="#"
        onclick="downloadFile(event)">Download</a>
    <script>

        const downloadFile = async e => {
            e.preventDefault();
            try {
                const response = await fetch(e.target.dataset.href);
                if (response.status !== 200) {
                    throw new Error(await response.text());
                }
                const blob = await response.blob();
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = e.target.dataset.href;
                document.body.appendChild(a);
                a.click();
                Promise.resolve().then(() => a.remove());
            } catch (e) {
                alert(e.message);
            }
        }



    </script>
</body>

</html>

Answer №2

When it comes to error handling, you have the flexibility to display error responses in any way you choose. Here's an example of how it can be done:

    error: function(xhr, status, error1) {
         var errorMessage = JSON.parse(xhr.responseText);
         console.log(errorMessage)
    }

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

Utilizing the content of an HTML element within Ruby embedded code - a comprehensive guide

Below is the code snippet in question: <% @groups.each do |group| %> <tr> <td id="groupid"><%= group.id %></td> <td><a href="#dialog" name="modal"><%= group.title %></a></td> </tr> &l ...

Exploring JSON data to locate specific characters with JavaScript

[ {"lastName":"Noyce","gender":"Male","patientID":19389,"firstName":"Scott","age":"53Y,"}, {"lastName":"noyce724","gender":"Male","patientID":24607,"firstName":"rita","age":"0Y,"} ] When comparing my input with the JSON data, I utilize a loop to search f ...

Utilizing a fallback option for HTML5 video with a flash player and the ability to manipulate the

My dilemma involves an HTML5 video where I am utilizing jquery to interact with the player using the code snippet: video.currentTime += 1;. However, when Internet Explorer switches to Flash plugins, my JQ commands cease to function. How can I manage and co ...

What is the best way to send an HTTP request in AngularJS to receive data in JSON format?

I am trying to create an AngularJS app that can send HTTP requests for JSON data. I have written the code in my index.html file to request JSON data using AngularJS, but for some reason, the JSON data is not being printed. When I check the console in Fire ...

Retrieve main page elements from an additional page called PageSlide

I have implemented the jquery PageSlide plugin as a menu feature on my website. The plugin opens a separate page on the side of the main page to function as a menu. However, I am facing a challenge in accessing the main page's elements from this side ...

Establish a connection to couchDB using JavaScript on the server side

I'm working on a piece of code that involves using Restify to set up a server in node.js and create specific routes. My goal is to interact with CouchDB by performing actions such as GET, POST, DELETE, and PUT. var restify = require("restify"); var s ...

execute action once element has finished loading - angular

I am looking for a way to trigger an angular function after a specific element has been displayed on the page. The challenge arises because this element is part of a Single Page Application (SPA) where its display is controlled by a series of events. Tradi ...

No value found for Req.file using the express-fileupload and multer libraries

I have exhausted all possible scenarios and attempted various variations and methods recommended in the documentation and from other sources like Stack Overflow. However, none of them seem to work -> I constantly receive req.file is: undefined Here is ...

How can I use jQuery UI to slide a div, while also smoothly moving the adjacent div to take its place?

Wishing you an amazing New Year! I am looking to create a smooth sliding effect for a div when a button is clicked. I want the adjacent div to slide alongside it seamlessly, without any clunky motions or delays. Currently, the adjacent div only moves afte ...

Searching for partial nodes

I came across a helpful tutorial that explains how to perform a partial search. My goal is to have it so that when someone enters the text geor, it can locate a user named george. db.stores.find({storeName : {$regex : /Geor/}}).pretty() However, I am str ...

Change the color of a specific day on the Arshaw Calendar using CSS

Can anyone help me with changing the color of the box in the month view in the arshaw calendar? I've been attempting to do so using this script, but my lack of expertise in javascript is proving to be a hurdle. The goal is for this script to be called ...

Getting the return value in JSP using JSP Ajax Servlet

When I click on one of the tables, another table is loaded using Ajax in my JSP: $("#tablesorter-demo tr").click(function(){ $('#tablesorter-demo tr').not(this).removeClass('hilite'); $(this).toggleClass(&apo ...

The event failed to initiate

I have an event that is fired when the number value changes in the <input type="number"> below: <input type="number" inputmode="numeric" pattern="[0-9]*" size="4" class="lorem" value="0" step="1"> <input type="button" class="minus" value=" ...

Retrieving specific data from nested arrays in Vue.js

I am currently working on Vue.js template development and facing an issue with filtering nested data in a faq section. When I try to add a search bar, the nested data array returns all data without proper filtering. Dom <v-container> <v ...

The method of altering a menu link in WordPress using jQuery varies according to whether the user is logged in or not

I need to update the last link on my menu. When a user is logged in, it should display a profile link; otherwise, it should show a sign-up link. ...

Utilizing Typescript Generics in Arrow Function to Combine Two Arguments

For instance, I am working with this code in a .tsx file extension const Add = <T,>(arg0: T, arg1: T): T => arg0 + arg1; const A = Add(1, 2); const B = Add('1', '2') However, I am encountering an issue, as there is an error m ...

I have to convert a JSON string that I received from a server into a particular JavaScript object

Hey everyone! I wanted to share some code I've been working on: $.ajax({ url: '@Url.Action("GetMerchantUsers", "Merchant")', dataType: 'json', success: function (json) { var mappedTasks = $.map(JSON.parse(json ...

gulp.watch executes tasks without following a specific sequence

Objective Develop a gulp.watch task to execute other tasks in a specific sequence Why this is unique While many have referred me to How to run Gulp tasks sequentially one after the other, my query differs as it pertains to using gulp.watch instead of gu ...

Avoid Refreshing the Page When Pressing the Like Button

I've been working on code for liking a post and saving the value to a database using server-side code. However, I'm running into some issues when the page refreshes after clicking the like button. I tried using event.preventDefault() in my JavaSc ...

Typescript double-sided dictionary: a comprehensive guide

Looking for a dual-sided dictionary implementation in TypeScript that allows you to retrieve values using keys and vice versa. An initial approach could be storing both items as keys: dict = {"key": "value", "value": "key"} But I am curious if there are ...