Handling Ajax errors
Introducing any kind of network interaction into an application brings along some degree of uncertainty. The user's connection could drop in the middle of an operation or a temporary server issue could interrupt communications. Because of these reliability concerns, we should always plan for the worst case and prepare for error scenarios.
The $.ajax()
function can take a callback function named error
to be called in these situations. In this callback, we should provide some kind of feedback to the user indicating that an error has occurred:
$(() => { $('#ajax-form') .on('submit', (e) => { e.preventDefault(); $.ajax({ url: 'https://api.github.com/search/repositories', dataType: 'jsonp', data: { q: $('#title').val() }, error() { $('#response').html('Oops. Something went wrong...'); } }); }); });
Listing 13.5
The error callback can be triggered for a number of reasons. Among these are:
- The...