W3docs

How to Manage a Redirect Request after a jQuery Ajax Call

In this JavaScript tutorial, you will read and learn detailed information about the method used for managing a redirect request after a jQuery Ajax call.

You can manage a redirect request after a jQuery Ajax call by using a JSON response.

For this pattern, the server returns a status code of 200 with a JSON object in the response body. On the client, JavaScript can use the JSON object to decide further actions. The browser processes the redirect and delivers a 200 code with the content of the redirect destination. If you perform an HTTP redirect, the redirect never triggers the Ajax success callback.

jQuery Example

$.ajax({
  type: "POST",
  url: reqUrl,
  data: reqBody,
  dataType: "json",
  success: function (data, textStatus) {
    if (data.redirect) {
      // data.redirect contains the string URL to redirect to
      window.location.replace(data.redirect);
    } else {
      // data.form contains the HTML for the replacement form
      $("#my-form").replaceWith(data.form);
    }
  }
});

Here we have an Ajax request with 2 possible responses where one redirects the browser to a new page, and the other replaces an existing HTML form on the current page with a new one. The JSON data object is constructed on the server to have 2 members: data.redirect and data.form.

You can also use window.location.href instead of <kbd class="highlighted">window.location.replace()</kbd>, but <kbd class="highlighted">window.location.replace()</kbd> is better than the first, as <kbd class="highlighted">replace()</kbd> does not keep the originating page in the session history.