Ways to prevent form submission while awaiting a server response in JavaScript

I am working on a form that submits data to a JSP page with Java code.

<form method="POST" id="form1" action"<%=login%>">
<input id="btn" type="submit" value="Log in" />

However, I have observed that if the user holds down the enter button or presses the login button multiple times, it creates new sessions and requests each time. Is there a way to prevent this behavior while waiting for a server response?

Thank you!

Answer №1

One way to handle this situation is by invoking the JSP page using an AJAX call. This approach allows you to update content on the page without having to reload it. You can achieve this by attaching an EventListener to the form element:

document.getElementById("form1").addEventListener("submit", event => {
    event.preventDefault();
    document.getElementById("btn").disabled = true;
    // Perform AJAX request here
});

After the AJAX request completes, remember to re-enable the button by setting its disabled attribute to false.

Answer №2

To avoid the action from occurring multiple times, you need to detect it as soon as possible

document.querySelector("#form1").addEventListener("submit", function(e) {
  if (this.dataset.active) {
    e.preventDefault;
    return;
  }
  this.dataset.active = 'true';
});

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

Guide: Looping through a typed Viewbag array - best practices

I have passed a List<AdminUsers> through the Viewbag to a view. This list is then assigned to a JavaScript variable and looped through. However, when debugging on the view, I noticed that the for loop is not being executed, even though I set a break ...

Getting Started with Angular 2 Installation

Looking for a straightforward way to incorporate Angular2 into a single HTML file without using Bower, NPM, NuGet, or other complex methods? EDIT: Thanks to Dieuhd's suggestion, I was able to make Angular 2.0 work using the following script referenc ...

RequireJs is failing to load a script based on its name

Recently, I delved into the world of RequireJs to enhance my understanding. However, I encountered a hurdle while trying to load a JavaScript dependency using its custom shortened name. Despite my efforts, I can't seem to figure out what I'm doin ...

What is the best way to retrieve ejs data within a form when implementing express?

When a user requests, the following HTML file is displayed in the code below. I also need to access the values of clubname and type inside the app.post() function in my app.js file. <!DOCTYPE html> <html> <head> <title><%= t ...

The 3D sphere in Three.js appears to have a 2D visual effect

Hey there! I've recently delved into the world of three.js and I'm working on creating a captivating scene with 3D spheres and a simple rotation using orbit controls. However, I've encountered an issue where the spheres appear flattened or 2 ...

Choose Default Value in Drop-Down List in AngularJS when Page Loads

Within the realm of Angularjs, there exists a DropDown: <select ng-model="category" ng-change="categoryChanged(category)" class="form-control" data-ng-options="category as category.name for category in categories"> <option value="">Se ...

Challenges encountered when using node.js to write binary data

I've been attempting to write the binary body of a request to a file, but I'm encountering some issues. Although the file is successfully created on the server, I'm unable to open it and am receiving a 'Fatal error: Not a png' mess ...

simpleCart - Utilizing a modal window for easy input and sending the shopping cart data to PHP in a multidimensional array

Currently, I am working with the simpleCart JavaScript shopping cart, but I have encountered a minor issue. When a customer clicks "checkout," a modal pops up requiring them to enter their contact information. Upon submitting the form, an email is sent to ...

The closure in question received an undefined Angular parameter

Here is something similar to what I have: $scope.fetchData = function(path, save_to) { $http({method: 'GET', url: 'http://localhost:8001/www-root/' + path}). success(function(data, status, headers, config) { ...

Simple Mobile-Friendly Tabs - mobile tabs are always visible

My JavaScript skills are not the best. I have been using Easy Responsive tabs and encountered an issue on the mobile version where clicking does not hide content, but only removes the "d_active" class and adds it to another element. I believe that if the ...

Tips for showcasing a dataset within a table using Angular.js ng-repeat

I am encountering an issue where I have to present an array of data within a table using Angular.js. Below is an explanation of my code. Table: <table class="table table-bordered table-striped table-hover" id="dataTable" > <tbody> ...

Steps for mocking an async action creator in Redux using Jest

I am currently working on writing a unit test for a redux async action creator using jest. asyncActions.js: const startSignInRequest = () => ({ type: START_SIGNIN_REQUEST }); // this is the action creator for successfully signing in a user export c ...

Storing the .NET Framework viewmodel in its own individual Javascript file

I have a question about structuring my design for SoC (Separation of Concerns). I currently have the following files: testController.cs testViewModel.cs testView.cshtml testScript.js Currently, I generate data in the controller, populate the testViewMod ...

Is it possible to transfer a variable from my javascript code to a jsp file?

Within a HTML file, I have created a variable in JavaScript consisting of an array with two entries - a latitude and a longitude. I am looking to use AJAX to send this variable and then utilize it in my JSP file to populate a form. Does anyone have any su ...

Link various data to various text boxes using a common ngModel property in Angular 8

In my project, I am working on creating a time-picker that will open when the user focuses on a text-box. The challenge I'm encountering is that although there are multiple text-boxes on a single page, binding the selected value from the time-picker u ...

Angular 2 - Utilizing multiple templates

Recently, I've been working on an application that requires the ability to load different templates dynamically. The standard template structure I'm using is as follows: <!doctype html> <html lang="en"> <head> <meta cha ...

Creating a Mocha+Chai test that anticipates an exception being thrown by setTimeout

Here is what I have: it('invalid use', () => { Matcher(1).case(1, () => {}); }); I am trying to ensure that the case method throws an exception after a delay. How can I specify this for Mocha/Chai so that the test passes only if an exce ...

Will a function take up space for each individual instance of a single class in JavaScript?

Let's think about this class: class A { num: number; str: string; someFunction(){console.log("SomeFunction called!")} } The memory allocation for the someFunction method is a question mark. Is this function stored in memory only once for all ...

Ways to modify Angular pipe without specifying data types

I am in the process of extracting an Angular pipe from an application to a library. The current pipe is tied to specific types, but I want to change it to use generic types while maintaining type safety. Original Pipe: import { Pipe, PipeTransform } fr ...

Utilizing Bootstrap 5: Executing JavaScript exclusively upon successful form validation

I've created a form with multiple input fields that are being validated using Bootstrap 5 validation. <form class="needs-validation asset-test" action="{{ url_for('asset_test') }}" method="post" novalidate> ...