Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching 302 FOUND in JavaScript

I use jQuery to make an AJAX POST request to my server, which can return HTTP response with status 302. Then JavaScript just sends GET request to this URL, while I'd like to redirect user to URL in this response. Is this possible?

like image 825
Alexander Solovyov Avatar asked Dec 16 '08 23:12

Alexander Solovyov


People also ask

Is HTTP 302 an error?

Conclusion. The HTTP error code 302 found indicates that a specific URL has been moved temporarily to a new location. Whenever visitors, Google robots, or other search engines access the original URL, 302 redirect delivers an automatic response indicating a new address.

What causes a HTTP 302?

What is an HTTP 302? The 302 status code is a redirection message that occurs when a resource or page you're attempting to load has been temporarily moved to a different location. It's usually caused by the web server and doesn't impact the user experience, as the redirect happens automatically.


2 Answers

The accepted answer does not work for the reasons given. I posted a comment with a link to a question that described a hack to get round the problem of the 302 being transparently handled by the browser:

How to manage a redirect request after a jQuery Ajax call

However, it is a bit of a dirty hack and after much digging around I found what I think is a better solution - use JSON. In this case, you can make all responses to ajax requests have the code 200 and, in the body of the response, you add some sort of JSON object which your ajax response handler can then use in the appropriate manner.

like image 193
Steg Avatar answered Sep 19 '22 14:09

Steg


I don't think so. The W3C says that HTTP redirects with certain status codes, including 302, must be transparently followed. Quoted below:

If the response is an HTTP redirect (status code 301, 302, 303 or 307), then it MUST be transparently followed (unless it violates security or infinite loop precautions). Any other error (including a 401) MUST cause the object to use that error page as the response.

As an experiment, I tried doing Ajax requests from various browsers (Firefox 3.5, Chrome, IE8, IE7, IE6) to a server giving a 302 status code, and showing the status in the browser's request object. In every case, it showed up as 200.

like image 21
Elias Zamaria Avatar answered Sep 16 '22 14:09

Elias Zamaria