Disable global Ajax events in jQuery

It is very easy to disable ajaxStart() and ajaxStop() for a single request. We can prevent all global ajax events in jQuery like ajaxStart, ajaxComplete, ajaxSuccess, ajaxError etc. To disable global ajax handler you have to use global: false

$.ajax({ url: 'YourWebservice.asmx/GetCurrentTime',
  global: false,
  type: 'POST',
  dataType: 'json',
  contentType: 'application/json',
  success: function (result) {
    alert('Success');
  },
  error: function (result) { alert('Error') }
});

CODE
<!DOCTYPE html>
<html>
<head>
  <title>jQuery With Example</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $('#btnClick').click(function () {
        GetTime();
      });
    });
    function GetTime() {
      $.ajax({ url: 'YourWebservice.asmx/GetCurrentTime',
        global: false,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        success: function (result) {
          alert('Success');
        },
        error: function (result) { alert('Error') }
      });
    }
    $('#container').ajaxStart(function () {
      alert('ajaxStart executed');
    });
    $('#container').ajaxComplete(function () {
      alert('ajaxComplete executed');
    });

    $("#container").ajaxError(function () {
      alert('Server Error');
    });
  </script>
</head>
<body>
  <button id="btnClick">Click</button>
</body>
</html>

3 comments :

  1. Would it be possible to stop the events in a $.get() or $.post() request?

    ReplyDelete
  2. Yes you can stop the events. You can also use abort() method.

    ReplyDelete
  3. Nice post. Keep sharing stuffs like this :)

    ReplyDelete