Using an AJAX/HTML/JavaScript approach to enable/disable a button for generating reports and then re-enabling it

A Spring-MVC controller is used to generate a PDF report when a get request is made. The controller includes headers such as "application/OCTET-STREAM", "Content-Disposition", and "attachment; filename=\"" + filename + "\"" in order to prompt the user for save/open action. The controller writes the generated PDF bytes directly to the response's output stream, returning a null ModelAndView.

The challenge lies in disabling the button responsible for triggering the report request after it has been clicked, and then re-enabling it once the report generation is completed to prevent double clicking.

My initial attempt at using prototype.org's Ajax.Request successfully handles the buttons but fails to deliver the PDF to the client. It seems that further steps need to be taken with the response, but I'm unsure of what to do next. Any suggestions or assistance would be greatly appreciated.

function displayPdf(button_b, pdf_url) {
   button_b.disabled = true;
   new Ajax.Request(pdf_url, {
       asynchronous:true,
       evalScripts:true,
       method:'get',
       onComplete: function(response) {
         button_b.disabled = false;
      },
      onFailure: function() {
          redAlert('crap');
     }
   });
}

Answer №1

To achieve all the functionalities you desire, considering that a download is necessary, one potential approach could be as follows:

<html>
<head>
    <script>
        function initiateDownload() {
            document.getElementById('downloadBtn').disabled = true;
            document.getElementById('downloadFrame').src = "http://www.ca3.uscourts.gov/opinarch/063575p.pdf";
        }
        function enableButton() {
            document.getElementById('downloadBtn').disabled = false; 
        }
    </script>
</head>
<body>
    <iframe id='downloadFrame' onload='enableButton()'></iframe>
    <button id='downloadBtn' onclick='initiateDownload()'>Download Now</button>
</body>
</html>

In essence, this solution involves directing the file to the iframe rather than using an AJAX request. Upon completion of the PDF loading, the iframe's onload event will trigger, re-enabling the button. It is advisable to utilize proper event listeners instead of the outdated inline ones demonstrated in this example.

Answer №2

Maybe you're looking to avoid users from clicking the button multiple times intentionally. One simple solution could be using a setTimeout function to re-enable the button after a certain delay.

Check out this example on how to use the setTimeout() method.

For instance, in your displayPdf function, you can add:

setTimeout("button-b.disabled = false", 4000);

This code snippet will keep the button disabled for 4 seconds after being clicked and then allow it to be clicked again.

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

When checking if el.text() is equal to "string", it will return false, regardless of the actual content of the element being "string"

Looking at the code snippet below, it seems that the else block is always being executed instead of the if block. The alert confirms that the variable state has the value 'payment' as expected. var state = $('.check-state').text(); ale ...

Shifting a div element around the webpage and letting it fall into place if it intersects with another div using plain JavaScript

Check out this jsFiddle link. Upon opening it, you will encounter a moveable div. However, I am looking to enhance this functionality by allowing the div to disappear if moved to the 'trash' area. Essentially, when you place the moveable div in t ...

Tips for turning off the auto save password option on browsers for user registration forms

Is there a way to prevent browsers from saving passwords on the add users form? I've tried using autocomplete="off" but it doesn't seem to work for saved passwords. I've searched extensively for a solution but haven't found the right on ...

Can you explain the distinction between Array() and [] in Javascript, and when would it be preferable to use one over the other?

Similar Question: Understanding the difference between "new Array()" and "[]" in JavaScript array declaration When working with JavaScript, you have the option to create a new array using: var arr = new Array(); or simply using: var arr2 = []; Wha ...

Choose all the items that are visible in the list using Angular

If you have the following ng-repeat: <ul class="list-group"> <ng-user-item ng-repeat="user in users | filter:search" user="user" ng-if="assigned.indexOf(user.id) < 0" ng-click="selectFunction(user);"></ng-use ...

What methods can be used to implement client-side validation on a file upload control in ASP.NET to verify if the filename includes special characters?

When working with the ASP.NET 3.5 platform, I encountered an issue while using a file upload control and an ASP button to upload files that contain special characters, such as (file#&%.txt). This caused the application to crash and display the followin ...

Trouble encountered when attempting to override styles in Material UI's TableRow

I am attempting to customize Material UI's default styles in order to create a margin between each TableRow. Despite my efforts, it appears that the override is not being reflected in the user interface. ...

Discovering uncategorized elements using javascript

Let's say I have a piece of HTML with some content that is not wrapped in any tags, like this: <html> <body> <p>text in a tag</p> other text outside any tag </body> </html> Is there a way to access the untagged el ...

Premature adjustment of images to window size changes

How can I make the images inside a divider move down when the right-end of the browser reaches them? Currently, they start moving down before the edge of the window is reached. Any suggestions on how to fix this? JSFIDDLE: https://jsfiddle.net/prtdaay1/2/ ...

Getting a user's group name from Azure Active Directory in an Angular application - a step-by-step guide

I have connected to Azure directory using ng2-adal (https://github.com/mazhisai/ng2-adal-QuickStart) and successfully obtained a group id in the format: "groups":["4ba2649e-20d2-40f4-a406-2ed897686403","43e19f05-c077-4716-b001-0ffb0d75fff8"]. Is there a w ...

Having difficulty adding a custom library from a repository into an Ember project as a dependency

I've been working on a WebGL library that I want to include as a dependency in an EmberJS project. It seems like I should be able to do this directly from the repository without creating an npm package, but I'm running into some issues. To illus ...

Tips for invoking a function to automatically load elements on a jQuery mobile website

I am looking to keep my navbar HTML markup in a centralized location for easy editing. Currently, the body content of my index.html file appears like this: <div data-role="page" id="SomePage"> <div data-role="header"> <h1>Thi ...

Generating meta tags in a web scraping tool within a front-end application using AngularJS

Running an AngularJS web app entirely on the client side presents a challenge when it comes to adding html meta tags for the FaceBook scraper. These meta tags need to be rendered from the server, without relying on client-side JavaScript. Currently, I&apo ...

Applying a CSS transition to transform properties excluding rotation effects

I'm looking to apply a transitional animation to an element's transform property without affecting the rotation. Here is the code snippet: <html> <head> <link rel="stylesheet" href="style.css"> <script src="script.js ...

Dynamic JavaScript Total Calculation

I have been struggling to update the total price for specific options. Even though the code was created by someone else and has worked fine for many users, I can't seem to make it work correctly. Any assistance would be greatly appreciated. Here is t ...

Leveraging server-side functionality with JavaScript

Recently, I have been enhancing my ASP.NET project by incorporating more JavaScript and AJAX functionality. In the process, I have adjusted parts of my HTML to be generated using JavaScript. However, this modification has made it challenging for me to acce ...

AngularJS is incapable of detaching forms from objects

Creating forms dynamically using ng-repeat and adding them to the vm.forms object is causing issues. When an item is removed from the array, the corresponding form is deleted but the key in the vm.forms object remains, leading to undefined errors. angul ...

Utilizing Vue.js to incorporate the isActive property to the class name within a v-for loop, along with implementing dynamic class names

I am currently using a loop to iterate through some data in my store.js file, and everything is functioning as expected. However, I would like to add a condition to check if the Vue instance is active before applying a specific class to the polygon element ...

Obtaining Data from an Array with Reactive Forms in Angular 4

Just starting out with Angular 4 and trying to figure out how to populate input fields with information based on the selection made in a dropdown. <select formControlName="selectCar" class="form-field"> <option value="">Choose a car&l ...

Incorporating ajax and jquery into html: Step-by-step guide

Previously, I inquired about implementing a show/hide functionality for a div that only renders when a specific link is clicked. (View the original question) Following some advice, I was provided with jQuery and AJAX code to achieve this: function unhide() ...