Question:
There is a code:
<script>
var clickedButtonValue;
$('button[type="submit"]').click(function() {
clickedButtonValue = $(this).val();
});
/* attach a submit handler to the form */
$("#commentadd").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
text = $form.find('textarea[id="userComment"]').val(),
number = $form.find('input[id="num_clear"]').val(),
url = $form.attr('action'),
term = clickedButtonValue;
/* Send the data using post */
var posting = $.post(url, {
like: term,
text: text,
num_clear: number
});
posting.done(function( data )
{
/* Put the results in a div */
var data1 = $(data).find("#comments");
var data2 = $(data).find("#getrating");
$( "#comments" ).html(data1);
$( "#getrating" ).html(data2);
$("#commentadd")[0].reset();
});
});
</script>
It is necessary to limit the sending of a post request when the button is clicked no more than once every 5 seconds.
Answer:
We set the variable fire
to true
at the beginning of the script. Before sending the post
, we check if fire = true
, execute the post
, set fire = false
and set the timer to set fire = true через 3 секунды
. Final code:
<script>
fire = true;
var clickedButtonValue;
$('button[type="submit"]').click(function() {
clickedButtonValue = $(this).val();
});
/* attach a submit handler to the form */
$("#commentadd").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
text = $form.find('textarea[id="userComment"]').val(),
number = $form.find('input[id="num_clear"]').val(),
url = $form.attr('action'),
term = clickedButtonValue;
/* Send the data using post */
if (fire = true) {
fire = false;
var posting = $.post(url, {
like: term,
text: text,
num_clear: number
});
setTimeout(function() {
fire = true;
}, 3000);
}
posting.done(function( data )
{
/* Put the results in a div */
var data1 = $(data).find("#comments");
var data2 = $(data).find("#getrating");
$( "#comments" ).html(data1);
$( "#getrating" ).html(data2);
$("#commentadd")[0].reset();
});
});
</script>