Get the file without having to reload the page with the help of JSP, Servlet, or Ajax

When a user clicks the download button, I have a file to be downloaded from the servlet without refreshing the page. How can this functionality be achieved? Below is my JSP code. Users input credentials in the search box to download the file, so the file searching logic is implemented in the servlet.

<form action="Download_Servlet" class="download" method="post">     
Search:<input type="text" name="dropdown" id="datedropdown">
<input type="submit" id="downloadRecords" value="Download">

Here is my servlet code:

response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=abc.csv");
ServletOutputStream out = res.getOutputStream();
for (Order traverse : orderMap.values()) 
    {   
        out.write(traverse.toString().getBytes());
        out.write("\n".getBytes());
        out.flush();
    }

The reason for using a loop is to write hundreds of records into the file and then flush it. The issue arises when the user clicks the download button because the page is trying to redirect, even though there is no code in the servlet to handle this redirection. The desired behavior is that when the download button is clicked, the file should be downloaded without the page being redirected.

Answer №1

See this code snippet :

function downloadWithAjax(url, data) {
    var $iframe,
        iframe_doc,
        iframe_html, 
        input_name;

    if (($iframe = $('#download_iframe')).length === 0) {
        $iframe = $("<iframe id='download_iframe'" +
                " style='display: none' src='about:blank'></iframe>"
               ).appendTo("body");
    }

    iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;

    if (iframe_doc.document) {
        iframe_doc = iframe_doc.document;
    }

    iframe_html = "<html><head></head><body><form method='POST' action='" +
                  url +"'>" +
                  "<input type=hidden name='" + input_name + "' value='" +
                  JSON.stringify(data) +"'/></form>" +
                  "</body></html>";

    iframe_doc.open();
    iframe_doc.write(iframe_html);
    $(iframe_doc).find('form').submit();
}

How to use it:

$(document).on('click', '#download_button_id', function(){
    downloadWithAjax('http://www.mridulahuja.com/uploads/1/3/8/6/13860206/handy_notes_v2.0.rar');
});

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

How can Angular's as-syntax be used to access the selected object?

When using syntax like ng-options="p.id as p.name for p in options" to select options, I encounter an issue. I require access to the variable p as well. This is necessary for displaying additional labels near inputs or buttons, or even making changes to in ...

JavaScript code snippet to remove a specific element from an array and store it in an object

I am looking to convert an array into an object, where each item in the array is separated into categories as shown below. let a=['monkey: animal','John:human', 'Rob:human', 'donkey:animal'] I expect the output to b ...

Utilizing MongoDB for mule caching within the community edition

I am currently working on integrating cache in Mule CE using MongoDB. I came across an insightful answer by @PontusUllgren on Stack Overflow, which inspired me to switch from EhCache to MongoDB. Here is the bean configuration I have: <spring:bean i ...

"Enhance user experience with a real-time autocomplete feature in React that triggers an API call whenever

Currently, I am facing a problem while working with React and the autocomplete component of Material-UI. I need assistance in resolving this issue. In the examples of autocomplete that I have come across, it seems like you need to preload all the elements ...

Angular 2: Dealing with NaN values from Snapshot Parameters and Services

I am facing difficulties in transferring parameters from one component to another using Angular2 router and activated route. Here is my API Service: getModels(makeNiceName: string): Observable<Models> { return this.http.get(this.baseURL + mak ...

Comparing background-color using .css() in jQuery/Js

I've been experimenting with creating angled divs on a webpage, where each basic panel is separated by an angled break. The idea is to have the background-image of one div flow smoothly into the background-color of the next div. Since I couldn't ...

Unable to disable background color for droppable element

For my project, I am working with two div boxes. My goal is to make it so that when I drag and drop box002 into another div box001, the background color of box001 should change to none. I have attempted to achieve this functionality using jQuery without s ...

Occasionally, when scanning a barcode into a Swing textfield, the characters may

We have observed an unusual phenomenon with barcode scanners and a Java Swing application running on Windows 7 with jre8. This issue is occurring across a large deployment of over 1000 PCs using various barcode scanner models. The barcodes being scanned re ...

In Java, handle request bodies in XML or JSON without resorting to String manipulation

In my current project utilizing Spring Boot and Java, I am faced with the challenge of calling multiple external services. Each of these services requires a complex JSON or XML body as input, with varying fields that may not always be required. Here are so ...

Here's a unique rewrite: "Strategies for handling exceptions gracefully within a loop without halting

In my Java code, I am using the following for loop: List<String> accountList=new ArrayList<>(); int colNo=3; for(int rowNo=1;rowNo<=tableRowNumber;rowNo++) { String accountName=getTableData(By.xPath(".//*[@id='accTable']/"), ro ...

Sending Data Through Button from navBar in React-Native-Router-Flux

I have been working on a project that utilizes `react-native-router-flux` and I am facing a challenge in passing an object through `props`. Typically, I would use `Actions.someKey({ someProp: object })` for navigation. However, in this case, I need to navi ...

Removing an item from an array while also updating one of its attributes in JavaScript

I am facing a challenge with this list of objects: const flights = [ { id: 00, to: "New York", from: "Barcelona", cost: 700, scale: false }, { id: 01, to: "Los Angeles", from: "Madrid", cost: 1100, scale: tru ...

Change an Eclipse project containing Java source files into a Gradle project

In the process of migrating all my java projects (223 projects) to gradle project, I am currently utilizing the Gradle Eclipse plugin, which has been developed by the SpringSource STS team. As it stands, the structure of all my java projects is as follows ...

What is the process for transferring the value from a list item to the search field box?

I have developed a Bootstrap/jQuery function that can display the item matching the user's search query. However, I am facing some challenges in making the selected item populate the search field or providing clear validation to the user once it is ch ...

Adjust the volume of the background music when transitioning from an activity to a service

I am currently learning about android development and have been tasked with incorporating background music into our app. I have successfully added background music using a service, but I am struggling to figure out how to dynamically change the volume of t ...

Execute a command and direct the input/output to designated files

My goal is to execute a child process in the background while also modifying its output (like adding timestamps) and directing it to specific files. Currently, I am approaching this task as follows: try { var out = fs.createWriteStream(`${this.logdir}/$ ...

I must create a dropdown and lift up feature similar to the one provided in the example

I am looking to implement a drop-down navigation bar on the top right and a pop-up button/links on the top left. The drop-down menu should appear when the screen size reaches a certain pixel width. If you can't see the drop-down navigation (NAV), adju ...

Exploring various layers of nested data

I am currently developing a comprehensive global data storage system for my application (specifically an Angular JS app - although this question pertains to JavaScript in general). I have established a 'service' that is responsible for setting t ...

Having an issue with my code in angular 12 where I am unable to successfully call an API to retrieve a token, and then pass that token to another API for further processing

Here is the code snippet containing two methods: getToken and validateuser. I am fetching the token from getToken and passing it as a parameter to validateuser. However, before retrieving the token, my second API call is being executed. ...

Does Node.js support backward compatibility?

There is a common belief that Node.js is backwards compatible, meaning scripts running in Node.js N should also work in Node.js N+1. I have been unable to find any documentation confirming this assumption. Is there another way to verify compatibility aside ...