1

My POST request handler can either return content that I load into a div or the browser is redirected. When I use jQuery's .post(), in the case of a redirect, instead of the entire page redirecting, the content returned from the redirect is loaded into the div:

var request = $.post('/my-post-url/');

request.done(function(response) {
  $('#my-div').empty();
  $('#my-div').append(response); // In case of redirect, response has new page's contents
});

To get around this, I use the code from this answer:

request.done(function(response) {
  if(xhr.responseURL != window.location.href.match(/(^[^#]*)/)[0])
  {
    location.href = xhr.responseURL;
    return;
  }

  $('#my-div').empty();
  $('#my-div').append(response);
});

This works fine, but I end up doing two GET requests for the same content: the first one is done automatically by the time I get inside the done handler, and the second is when I set location.href. Is there a way to either prevent this extra GET request and/or redirect the ENTIRE page on a redirect?

user2233706
  • 6,148
  • 5
  • 44
  • 86
  • No. There is not – mplungjan Jun 16 '17 at 17:01
  • Doesn't seem to be possible. See https://stackoverflow.com/questions/228225/prevent-redirection-of-xmlhttprequest – Barmar Jun 16 '17 at 17:01
  • Instead of returning plain HTML or a redirect, return a JSON object that indicates whether the client should redirect or display the HTML. `{ type: "html", data: "content to display" }` or `{type: "redirect", data: "URL to redirect to" }` – Barmar Jun 16 '17 at 17:05
  • Barmar that was what I wanted to do next but wanted to see if this was possible. – user2233706 Jun 16 '17 at 18:06

0 Answers0