Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop sending ajax request without page refresh

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);
        }
    });
});
like image 881
Mahmood Rehman Avatar asked Feb 14 '13 04:02

Mahmood Rehman


2 Answers

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);
        } 
    });
});
like image 200
Ja͢ck Avatar answered Nov 03 '22 01:11

Ja͢ck


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);
     } 
  });
}());
like image 31
Ryan Avatar answered Nov 02 '22 23:11

Ryan