5

I want to redirect to the target using the Location header with jQuery 1.7.

My code looks like this

$('#creationLink').click(function(){
  $.ajax({
    type: 'POST',
    url: '/',
    success: function(data, textStatus, xhr) {
      window.location = xhr.getResponseHeader("Location");
    }
  })
});

... but it does not work. xhr.getResponseHeader("Location") is null.

HTTP headers:

POST / HTTP/1.1
Host: localhost:9000
X-Requested-With: XMLHttpRequest
Content-Length: 0

HTTP/1.1 302 Found
Content-Type: text/plain; charset=utf-8
Location: http://localhost:9000/vIRdD0PdWp4/bearbeiten
Content-Length: 0

How can I redirect using the location header?

deamon
  • 89,107
  • 111
  • 320
  • 448
  • What does the response look like? Can you dump the data from the Chrome network tab? – Jivings Jun 04 '12 at 20:10
  • try `console.log(xhr);` what does that show? – Doug Molineux Jun 04 '12 at 20:10
  • Are you sure that the page you're referencing is sending a `Location` header? – Death Jun 04 '12 at 20:12
  • From the [MDN](https://developer.mozilla.org/en/xmlhttprequest#getResponseHeader%28%29): _Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response._ – Zuul Jun 04 '12 at 20:15
  • possible duplicate of [jquery getResponseHeader always returns 'undefined'?](http://stackoverflow.com/questions/4369987/jquery-getresponseheader-always-returns-undefined) – Zuul Jun 04 '12 at 20:27

1 Answers1

16

AFAIK, browsers are supposed to, during an XHR, transparently follow the redirect in the response header. That is, the XHR will actually look at the response, see the Location header, and proceed to magically run a second request for that URI. Only when it has the result of that will it give you anything at all, and what it gives you is the result of the second request.

See this stackoverflow answer!

So, if you need a redirect feature, you'll have to make the thing you request return the target URI in some other way, e.g. as a JSON response.

See this stackoverflow solution!

PS. reference: http://www.w3.org/TR/XMLHttpRequest/#infrastructure-for-the-send-method

Community
  • 1
  • 1
Jan Krüger
  • 17,870
  • 3
  • 59
  • 51
  • 6
    @Jan Krüger, I've been reading about this and found an answer an a solution for this problem. Since there was no need to post a new answer here with the same content as yours, I've placed the links to complement your information! – Zuul Jun 04 '12 at 20:31