How can I prevent an AJAX request if it's within 5 seconds of the previous request?
I have a comment field that allows the user to leave comments by pressing enter. It does it with a query AJAX
(jQuery). Is there a good way to prevent an event from burning if it is within 5 seconds after the previous comment and show the message? Or does it have to be handled server side?
source to share
This should definitely be handled on the server as well, because the javascript restrictions can be bypassed. But a javascript solution can save traffic and time:
var last_req = 0;
var limit = 5000; //miliseconds
function send_comment() {
var time = new Date().getTime();
if(time-last_req<limit) {
alert("Wait please");
return false;
}
last_req = time;
$.get("comment.php", {/*data*/}, function() {});
}
source to share
Depending on your use case, you can use throttle
either debounce
:
http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/
Or check out this post:
source to share
This can be done simply with a boolean flag ...
// declare this globally at the top of your script
var allowAjax = true;
// this would be in some event handler (on enter keypress, for example)
if (allowAjax) {
$.ajax({
...
...
});
} else {
// show message saying to wait
}
allowAjax = false;
setTimeout(function() {
allowAjax = true;
}, 5000);
source to share
This might help you what you want to do: http://jeykeu.wordpress.com/2012/03/09/jquery-prevent-multiple-ajax-requests/
You need to modify it a little to add a timer and use it for testing to see if a new request is possible.
source to share