How to manage a redirect request after a jQuery Ajax call
Redirect after a jQuery Ajax call by setting window.location.href
within the success
callback:
Our server response consequently dictates our following action: a redirect, or an HTML content refresh.
In-depth: handling varied server responses
In the wondrous world of Ajax, we frequently encounter various server responses. Fear not, for we shall conquer the handling of session timeouts, redirects, and HTML partial updates.
Using JSON responses to indicate redirect
A clever server could tell us a redirect is necessary via a JSON object bearing a redirect property.
Delving deeper with complex Ajax calls
For dealing with more convoluted situations, turn to jQuery.ajax()
. Here's a novel way to handle status codes with élan:
Special headers and status codes.
Engage custom headers or non-standard status code 278
to efficiently amanage redirects without worrying about those pesky browsers or middlewares that interpret HTTP 301/302 redirects on their own.
Coping with expired sessions, gracefully
Copology 101: Always deal with session timeouts gracefully. To do this, check the custom header or status code to ascertain if a session has expired:
When updates are needed, but not redirections
When a redirect isn't necessary, it's probably just an update of a portion of the page that's needed. Replace the relevant HTML block with the server response:
For boosting your understanding of these methods and their respective concepts, please check out these references. They'll take you straight to "street smart" from "book smart".
Was this article helpful?