Friday, October 5, 2012

jQuery - Add an ajax request indicator to a page in a fixed position for debug purposes

This is a handy code snippet for adding a debug indicator to a page that uses jQuery for ajax requests. The indicator appears as a little 5px square in the top right hand corner of the page.

  • If the square is grey, then the request is in progress and has not received a response yet.
  • If the square is green then the response was received ok.
  • If the square is red then there was an error (either a timeout or an error response from the server).

$(function () {
//add a requesting indicator to the page
$(document.body).append(
$('<div id="requesting" />').css({
top: '0px',
right: '0px',
height: '5px',
width: '5px',
'background-color': 'gray',
position: 'fixed'
}));
//set it up to show/hide if requests are in progress
$("#requesting").bind("ajaxSend", function () {
$(this).show();
$(this).css('background-color', 'gray');
console.log("Sent Request");
}).bind("ajaxSuccess", function () {
$(this).css('background-color', 'green');
console.log("Response Received OK");
}).bind("ajaxError", function () {
$(this).css('background-color', 'red');
console.log("Error Receiving Response!");
}).bind("ajaxComplete", function () {
$(this).fadeOut('slow');
console.log("Request Complete");
});
});

No comments:

Post a Comment