Error handling
So far, we have only dealt with successful responses to Ajax requests, loading the page with new content when everything goes as planned. Responsible developers, however, should account for the possibility of network or data errors and report them appropriately. Developing Ajax applications in a local environment can lull developers into a sense of complacency since, aside from a possible mistyped URL, Ajax errors don't just happen locally. The Ajax convenience methods such as $.get()
and .load()
do not provide an error callback argument themselves, so we need to look elsewhere for a solution to this problem.
Aside from using the global .ajaxError()
method, we can react to errors by capitalizing on jQuery's deferred object system. We will discuss deferred objects more fully in Chapter 11, Advanced Effects, but, for now, we'll simply note that we can chain .done()
, .always()
, and .fail()
methods to any Ajax function except .load()
, and use these methods to attach the relevant...