Submitting multiple AJAX requests that eventually trigger the submission of a form leads to unforeseen outcomes

My apologies for the vague question title, but I am struggling to articulate my query.

Imagine a scenario where a form on a webpage is used to add data to a list. Each time new data is added, it is first saved in a database and then the page is refreshed (not an ideal design, but let's go with it for now!).

There is a button that triggers an AJAX request. Upon receiving the request, the server performs some checks and responds with success. In the AJAX success function, the form data is submitted from the input field. So essentially, two calls are made to the server - one for the AJAX request and another for the form submission. It takes around 3 seconds for the browser to display the updated list.

Now, picture this - I rapidly click the button three times before the first AJAX request completes (let's say the server-side method of the request has a delay of 1000ms). After about 6 seconds, the page refreshes and the list shows the same data repeated thrice. I understand why this happens due to concurrent execution on the server side, but what puzzles me is the delay when the first AJAX request hits a "redirect" or "render" method. Why does it take approximately 6 seconds to render the page? While I can overlook the inefficiency in the coding structure, I am genuinely curious about this phenomenon and how servers handle multiple AJAX requests during page rendering.

Example Code:

View:

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>dfsfsd</title>
    <g:javascript library='jquery' />
    <r:layoutResources/>
</head>
<body>

<g:form url="[action:'addToDatabase',controller:'main']" id="addDataForm">
    <label>Data Name</label>
    <input type="text" name="dataName" id="inputDataName">
</g:form>
    <button type="button" id="addToDatabaseButton">Add Data</button>

<script>
    $("#addToDatabaseButton").on( "click", function() {
        $.ajax({
            url: "${createLink(controller: "main", action: "ajaxCheck")}",
            type: "post",
            cache: false,
            success: function () {
                $("#addDataForm").submit();
            }
        });
    });

</script>

</body>
</html>

Server side:

class MainController {

    def index() {
        []
    }

    def addToDatabase() {
        log.error ("We recieve $params.dataName")
        sleep 2000
        redirect(controller: "main", action: "index")
    }

    def ajaxCheck (){
        def map = [:]
        map.put("result","OK")
        render map as JSON
    }
}

When adding an item to the database, there is a simulated 2-second delay, with logs displaying the inserted item. As observed, upon clicking "Add Data" after entering "Name A," the value appears immediately, followed by a 2-second delay before the page refreshes. However, pressing the button repeatedly resets this 2-second delay, leaving me puzzled as to why the browser doesn't show multiple refreshes and rather just a single instance?

https://i.sstatic.net/2kNTu.gif

Answer №1

Could this issue possibly be related to your browser's caching of requests? If you keep sending the same request, it may get cached on the fly.

If you're using Firefox, please go to Dev tools -> Network tab -> and check the box that says Disable cache. A screenshot has been provided for reference:

https://i.sstatic.net/uVdAy.png

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

The successful completion of the Ajax post method reveals a difference in the sequence in which data is posted and retrieved

Within my code, I have dynamically created textboxes with various ids. In JavaScript, I am able to fetch the values of these textboxes one by one. Everything seems to be working perfectly up until this point. However, when I pass this data using an AJAX ...

What is the best way to share props with all routes in vue.js?

I need to make sure that all components have access to the BASE_URL variable. Here is an example of my App.js: <template> <router-view></router-view> </template> <script> import addJoke from './components/addJoke.vue&ap ...

Trigger a Tabulator event when a checkbox is selected in Vue 3

Currently, I am utilizing Vue3 along with Tabulator (5.2.7) to create a data table using the Composition API. In the following code snippets, I have excluded irrelevant parts of the code. //DataTable.vue <script setup> import { TabulatorFull as Tabu ...

Determining the selected and active tab within a dynamically generated set of tabs

I am curious about how to identify the selected language tab when uploading a file from a set of dynamically generated tabs. It is important for me to capture and pass on the language that has been chosen. In this scenario, I have specifically clicked on ...

Designing a self-contained web component structure using an Immediately Invoked Function Expression (IIFE

I have developed a custom web component to display gists in any HTML content. Starting with the Lit Element Typescript Starter Project as a base, I customized the rollup.config.js file. The output format was changed to iife for easier script tag accessib ...

Guide on redirecting to a specific tab data target in Symfony 5

When a user is on the 3rd tab and clicks on a DELETE button, I want to redirect the user back to the same 3rd tab on the page. **Template:** <nav> <ul class="nav nav-tabs"> <li class="nav-item"> ...

Oops! An error occurred while using the Google Maps API. Let's fix this hic

I recently encountered an issue on my website where the Google Map displayed suddenly showed an error message saying: "Oops! Something went wrong. This page didn't load Google Maps correctly. See the JavaScript console for technical details." Afte ...

issue with conditional statement in Vue.js

In my Vue.js code, I have implemented a v-if statement wrapped around a template tag that is supposed to display a specific message only when the signup type is a referral. Within this template tag, there are nested v-if statements for further conditions. ...

reCAPTCHA v3 - Alert: There are no existing reCAPTCHA clients available

After coming across a similar issue on Stack Overflow (link to the question here), I attempted to implement reCAPTCHA on my website to combat spam emails received through the form. Despite following Google's instructions, I encountered an error that p ...

Sending user input from an input field to a Node JS backend using AJAX for implementing typeahead feature

Implementing a typeahead functionality can be quite challenging, but with the right code, it can be achieved effortlessly. Here is an example of the HTML page: ... ... <input id="product" name="product" type="text" class="form-control" placeholde ...

What are the steps to integrating JavaScript functions into an HTML document?

Struggling with integrating a JavaScript function from one file into an HTML file? I'm having trouble getting it to work and suspect it has something to do with making the JavaScript accessible in the HTML. The function is meant to sum up values taken ...

It appears that the slice function is not functioning correctly within an array of functions

My code includes a function called UIAlerts: function UIAlerts() {} I then use the prototype methodology to assign a variable to this function: UIAlerts.prototype.questions = [] Next, I add a function to this array: UIAlerts.prototype.questions.push(f ...

Progress Indicator on my online platform

I've been attempting to remove a loading bar from my website, but I can't seem to locate it in the site files. I even tried using Google Chrome's inspection tool, but I couldn't pinpoint the loader. Can someone please assist me? Visit ...

What is causing the specific sequence in which my code prints? (Exploring Javascript promises)

Can anyone help me understand promises and asynchronous programming better? I am confused because the code provided prints "1 2 0" instead of "2 1 0". Shouldn't f1 be executed only after f2 logs "2" to the console in the third block of code? const f1 ...

The premature reveal of the back side in the Kendo UI flip effect on Internet Explorer

Currently, I am in the process of creating a BI dashboard for a business application using JavaScript Kendo UI version v2014.1.416. Unfortunately, I have encountered an issue with certain visuals while testing on IE11. I must mention that due to practical ...

Adding a task to my database successfully through Postman integration

I'm having trouble implementing the code for my todo app using React. I am encountering an issue with adding a new todo to the database using the handleSubmit function. Oddly enough, it works fine when testing with Postman, but not when trying to inpu ...

Is there a way to automatically display the first highlighted fragment in reveal.js?

Is it possible to have the first fragment automatically visible in reveal.js? I am utilizing the text colour highlight feature in reveal.js to make the most recent fragment appear with a slightly brighter color, drawing attention to that specific section. ...

How to execute a system command or external command in Node.js

I am encountering an issue with Node.js. When using Python, I would typically perform an external command execution like this: import subprocess subprocess.call("bower init", shell=True) Although I have explored child_process.exec and spawn in Node.js, I ...

The extracted text from the window appears to be blank

When attempting to enclose a selected string between two characters, I am encountering an issue. For example, when selecting 'test' and clicking on the change button, the selected text should change to 'atestb'. However, although I am a ...

Populate the location in Javascript using PHP data

I have a MySQL database containing latitude and longitude values. I am attempting to display these pairs as markers on a map. The JavaScript code for the Google Maps locations is provided below: var locations = [{lat: 36.53256989, lng: -6.29461908}, {lat: ...