Explain Codes LogoExplain Codes Logo

How to manage a redirect request after a jQuery Ajax call

javascript
ajax
redirect
server-response
Anton ShumikhinbyAnton Shumikhin·Sep 13, 2024
TLDR

Redirect after a jQuery Ajax call by setting window.location.href within the success callback:

$.ajax({ type: 'POST', url: 'path/to/your/api', data: { // Payload }, success: function(data) { // Let servers response decide if redirect is needed if(data.redirect) { window.location.href = data.redirect; } else { // Changing HTML content with "appendChild()" like a proud parent $('#yourElement).html(data.form); } } });

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.

// Server side pseudo-code if (userIsAuthenticated) { response.json({ success: true, redirect: '/dashboard' }); } else { response.json({ success: false, form: loginFormHtml }); }

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:

$.ajax({ // options... }).done(function (data, textStatus, jqXHR) { if (jqXHR.status === 278) { window.location.href = data.redirect; // 278: The server knows best } else { $('#formContainer').html(data.form); // For we anyway asked for it } }).fail(function(jqXHR) { if (jqXHR.status == 401) { // 401: This isn't Hogwarts window.location.reload(); // Transmogrify to login } });

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.

// Server-side code for setting a custom status code response.status(278).json({ redirect: '/user/dashboard' });

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:

$.ajax({ // options... error: function(jqXHR) { var sessionStatus = jqXHR.getResponseHeader('X-Session-Status'); if (sessionStatus === 'expired') { window.location.href = '/login'; // Redirect to login } } });

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:

// Server-side pseudo-code response.json({ form: newFormHtml }); // Front-end handling $.ajax({ // options... success: function(data) { if (!data.redirect) { //When no redirection, replace this part of the DOM // It's like seeing your housekeeping efforts pay off $('#formContainer').html(data.form); } } });

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".