<html>
<head></head>
<body>
<button onclick="ajaxcall()">Call the function</button>
</body>
<script>
function ajaxcall()
{
$.ajax({
url: 'insertdata.php',
data: {
userdata:userdata
},
type: 'POST',
success: function(response) {
//I have been using the response
}
});
}
</script>
</html>
<?php
$userdata = $_POST["userdata"];
// I have been getting userdata from ajax using post method
// Then I inserting to my aws database using api and it will take 2 to 5 seconds to get response from the api
?>
From the html code you can see that when I click the button, I have been calling "ajax" and sending the data to the "insertdata.php" and insert the data into the database inside "insertdata.php" file using "api"
When I click the button it's calling the ajax and wait for the response for 2 seconds.
After I click the button simultaneously The ajax is running one by one so it's taking too long to finis the process
What I need is when I click the button second time, It should run Parallel with the first ajax call instead of waiting to finish the first ajax call.
1.When I click the button for 5 times it takes 2 second to finish the ajax call so it's totally taking time 10 seconds.
There is no reason why you should be waiting for clicking the button while one Ajax process is still running. The following simulates a backend process with a random processing time between 0 and 2 seconds. Simply click the button several times and see what happens.
var num=1;
$("button").click(function(){
let n=num++
setTimeout(function(){
$.ajax({url:"https://jsonplaceholder.typicode.com/users/",data:{userdata:n},type:"POST",
success:function(res){
$("#log").append(" "+res.userdata);
}
})
},Math.random()*2000)
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<button>send data></button>
<div id="log"></div>
The numbers will not necessarily appear in sequence, as some calls will "overtake" others (depending on their different running times). But they will all appear in the log section.