In my project, I have an input box that triggers an ajax request with every key press. This means if I type the word "name," there will be a total of 4 requests sent out. However, what I really need is to only execute the latest request. So even if I enter "name," I want only the last request to be processed.
I have come up with a solution for this issue which involves using the click method as a simple example:
JavaScript code snippet:
var callid = 1;
function ajaxCall(checkval){
if(checkval == callid){
$.ajax({
type: 'post',
url: baseurl + "test/call_ajax",
data: {
val: "1"
},
success: function(data) {
console.log(data)
}
});
}
}
function call(){
var send = callid+=1;
setTimeout( function(){ ajaxCall(send) } , 500);
}
HTML script:
<a href="#" onclick="call()" > Call ajax </a>
The current implementation works perfectly fine, but I'm wondering if there's a way to further enhance it. Any suggestions or ideas are welcome!