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?