Home > Articles > Open Source > Ajax & JavaScript

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

Recipe: Handling Page Redirects

You might expect a similar result when you encounter a redirect code. Listing 5.7 investigates what happens in this case.

Listing 5.7. Receiving Content After an Implicit Redirect

00 <!DOCTYPE html>
01
02 <html lang="en">
03 <head>
04   <title>Test case: redirect</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('redirect')
24     .done(function(data, xhr) {
25       $('#target').append('Successfully redirected. . . ' +
26                   'returned data is ' + data.name);
27     })
28     .fail(function(xhr, text, error) {
29       $('#target').append('Redirect failed. Code ' +
30                   xhr.status + ' and text ' + text);
31     });
32
33   });
34
35 });
36 </script>
37 </body>
38 </html>

In this case, the AJAX request is successfully redirected to the new URL. The resulting values are picked up by the done() handler. In this example, this is exactly what we want.

However, if you do not want to be redirected and know that something is wrong, you might be out of luck. It seems like jQuery has nothing to do with the automated redirect handling. The browser does this for you according to specification.

In some use cases, a redirect is used to ask for further details from the end user, such as login credentials. In these cases, you do not want the AJAX request to be redirected under the hood. Instead, you want to catch the redirect and pass it on to the full browser screen.

Under these circumstances, if you have no control over the server, you are out of luck. If you do have control over the server, you should find a different way to pass the direct back to the AJAX call. Consider making it part of the content payload. Some libraries have invented new non-standard HTTP status codes. That should be considered bad practice and can cause unexpected results with proxies and caches.

  • + Share This
  • 🔖 Save To Your Account