ajaxSend() Method in jQuery ajaxSend() Method in jQuery

ajaxSend() Method in jQuery

.ajaxSend() – The ajaxSend() method specifies a function to run when an AJAX requests is about to be sent.

Whenever an Ajax request is about to be sent, jQuery triggers the ajaxSend event. Any and all handlers that have been registered with the .ajaxSend() method are executed at this time.

Syntax

$(document).ajaxSend(function(event,xhr,options))

To observe this method in action, we can set up a basic Ajax load request:

<div class="trigger">Trigger</div>
<div class="result"></div>
<div class="log"></div>

We can attach our event handler to any element:

$('.log').ajaxSend(function() {
  $(this).text('Triggered ajaxSend handler.');
});

Now, we can make an Ajax request using any jQuery method:

$('.trigger').click(function() {
  $('.result').load('ajax/test.html');
});

When the user clicks the button and the Ajax request is about to begin, the log message is displayed.

All ajaxSend handlers are invoked, regardless of what Ajax request is to be sent. If we must differentiate between the requests, we can use the parameters passed to the handler. Each time an ajaxSend handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request. For example, we can restrict our callback to only handling events dealing with a particular URL:

$('.log').ajaxSend(function(e, xhr, settings) {
  if (settings.url == 'ajax/test.html') {
    $(this).text('Triggered ajaxSend handler.');
  }
});

Example:

Show a message before an Ajax request is sent.

$("#msg").ajaxSend(function(evt, request, settings){
        $(this).append("<li>Starting request at " + settings.url + "</li>");
      });
<!DOCTYPE html>
<html>
<head>
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
$(document).ready(function(){
 $(document).ajaxSend(function(e, xhr, opt){
 $("div").append("<p>Requesting " + opt.url + "</p>");
 });
 $("button").click(function(){
 $("div").load("demo_ajax_load.asp");
 });
});
</script>
</head>
<body>

<div><h2>Let AJAX change this text</h2></div>

<button>Change Content</button>

</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *