␡
- Recipe: Setting Up an Example Server in Node.js
- Recipe: Performing a GET Request
- Recipe: Loading HTML Directly
- Recipe: Handling the Result by Using Promises
- Recipe: Handling Server Errors
- Recipe: Catching Page-not-Found Results
- Recipe: Handling Page Redirects
- Recipe: Setting Request Timeouts
- Recipe: Passing HTTP Headers
- Example: Validating Form Input on the Server Side
- Recipe: Loading XML
- Recipe: Listening to AJAX Events
- Recipe: Reading JSONP from an External Server
- Summary
This chapter is from the book
Recipe: Listening to AJAX Events
Similar to mouse, keyboard, and scroll events, in jQuery, AJAX requests generate AJAX events. You can use these to generate status indicators on screen so that the visitor knows that work is in progress. Listing 5.12 shows a basic event log for AJAX events.
Listing 5.12. Displaying all AJAX Events
00 <!DOCTYPE html> 01 02 <html lang="en"> 03 <head> 04 <title>AJAX related event handlers</title> 05 </head> 06 <body> 07 08 <h2>Press the button to perform the request.</h2> 09 10 <button id="trigger">GET</button> 11 <br> 12 <div id="target"> </div> 13 <div id="log"> </div> 14 15 <script src="https://code.jquery.com/jquery-1.7.2.min.js"></script> 16 17 <script> 18 // please externalize this code to an external .js file 19 $(document).ready(function() { 20 21 $('#trigger').click(function() { 22 $('#target').load('test-snippet.html'); 23 }); 24 25 $.each(('ajaxError ajaxSend ajaxStart ajaxStop ' + 26 'ajaxSuccess ajaxComplete').split(' '), 27 function (i, name) { 28 $('#log').bind(name, function(event, xhr) { 29 $(this).append('Event: ' + event.type + '<br/>'); 30 }); 31 }); 32 }); 33 </script> 34 </body> 35 </html>
Watch the order in which the events arrive when you click the button. This means you can respond in several stages of the AJAX request. The events also allow you to modify or add request parameters if you need to from a central location.