Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between Local Events and Global Events in jQuery?
Ajax requests produce a number of different events that you can subscribe to. There are two types of events:
Local Events
These are callbacks that you can subscribe to within the Ajax request object. Local events are specific to individual Ajax requests and are defined as callback functions within the $.ajax() method options.
Example
Here's how to use local events in jQuery Ajax ?
$.ajax({
url: "data.html",
beforeSend: function(){
// Handle the beforeSend event
console.log("Request is about to be sent");
},
success: function(data){
// Handle successful response
console.log("Data received: " + data);
},
complete: function(){
// Handle the complete event
console.log("Request completed");
},
error: function(){
// Handle errors
console.log("An error occurred");
}
});
Global Events
These events are broadcast to all elements in the DOM, triggering any handlers which may be listening. Global events allow you to set up centralized handling for all Ajax requests on your page.
Example
You can listen for global events like so ?
$("#loading").bind("ajaxSend", function(){
$(this).show();
console.log("Ajax request started - showing loader");
}).bind("ajaxComplete", function(){
$(this).hide();
console.log("Ajax request completed - hiding loader");
});
Disabling Global Events
Global events can be disabled for a particular Ajax request by passing in the global option ?
$.ajax({
url: "test.html",
global: false,
success: function(data){
console.log("This request won't trigger global events");
}
});
Conclusion
Local events are specific to individual Ajax requests and defined within the request object, while global events are broadcast to all DOM elements and provide centralized Ajax event handling across your entire application.
