Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

Recipe: Catching Page-not-Found Results

Similarly, Listing 5.6 tests what happens when the page is not found.

Listing 5.6. Recognizing a Page-not-Found Code

00 <!DOCTYPE html>
01
02 <html lang="en">
03 <head>
04   <title>Test case: page not found</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">
13
14
15 <script src="http://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
23     $.ajax('not-found')
24     .done(function(data, xhr) {
25       $('#target').append('Unexpected success... ' +
26               '(actually not a good thing)');
27     })
28     .fail(function(xhr, text, error) {
29       $('#target').append('Failed as expected (good!). Code ' +
30       xhr.status + ' and text ' + error);
31     });
32
33   });
34
35 });
36 </script>
37 </body>
38 </html>

As expected, again, the fail() callback is called, only this time with different parameters. Although you could check the xhr.status for a specific error code, jQuery provides a setting in ajax() that looks specifically at HTTP codes. The following snippet of code could be used in the previous example, replacing line 23.

$.ajax('fail-on-purpose', {
    statusCode: {
        404: function() {//insert 404 handling function here},
        500: function() {//insert 500 handling function here}
    }
})

When you remove the comments and insert your own code, the code will be run when either a 404 or 500 HTTP status code is returned. If you leave the fail() method in place, it will also execute, giving you another error handling point.

  • + Share This
  • 🔖 Save To Your Account