I created ajax request that sends some data to php file on button click event. Now after submitting data I want to restrict the ajax request not to send the data again and again by clicking the button. It sends the data only on page refresh ( means send data one time on page load ). How can I stop such requests. My ajax code is as follow :
$(".button").click(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
cache: false,
url: 'my/ajaxrequest.php',
data: {
result: 'hi test data'
},
success: function (resp) {
$("#result").html(resp);
}
});
});
Just replace .click()
by .one()
This will prevent multiple clicks from running your $.ajax()
again.
$(".button").one('click', function(e) {
e.preventDefault();
$.ajax({ ... });
}
If you need to perform a post on page load only, you can simply move the $.ajax()
call from the click handler into the document ready function:
$(function() {
$.ajax({
type: 'post',
cache: false ,
url: 'my/ajaxrequest.php',
data: { result : 'hi test data' },
success: function(resp) {
$("#result").html(resp);
}
});
});
A deeper analysis could restrict the ajax call to one successful response (i.e. was the status 200 && did it return the result you're looking for? If so you can put this code in the success
function of the XHR function: requestLog.sendStatus = true;
if you only want to allow the ajax request to initialize once then put this ( requestLog.sendStatus = true;
) right after the e.preventDefault
If you want to only allow the ajax call to be prevented if the their was in fact a succesful response then put the requestLog.sendStatus = true
in the success
function of the ajax object.
var requestLog = {};
requestLog.sendStatus = false;
$(".button").click(function(e) {
e.preventDefault();
if(requestLog.sendStatus) return;
/* requestLog.sendStatus = true; */
$.ajax({
type: 'post',
cache: false ,
url: 'my/ajaxrequest.php',
data: { result : 'hi test data' },
success: function(resp) {
$("#result").html(resp);
requestLog.sendStatus = true;
}
});
});
You want to run it on page load only once? Try this:
(function() {
$.ajax({
type: 'post',
cache: false ,
url: 'my/ajaxrequest.php',
data: { result : 'hi test data' },
success: function(resp) {
$("#result").html(resp);
}
});
}());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With