How to Manage a Redirect Request after a jQuery Ajax Call

You can manage a redirect request after a jQuery call by using an approach by JSON.

All the responses to Ajax requests have the status code 200 and the body of the response containing a JSON object that is constructed on the server. 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 trigger the Ajax success callback.

Here is a jQuery code:

$.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 window.location.replace(), but window.location.replace() is better than the first, as replace() does not keep the originating page in the session history.


Do you find this helpful?

Related articles