I have an AJAX call to a server endpoint that does a 301 redirect to the same page, but with a trailing slash.
Does the browser follow redirects when called with AJAX or does it ignore them? In my case it doesn't follow them, but I figured it might be something from the server config.
ajax appears to always follow redirects. How can I prevent this, and see the redirect without following it? There are various questions with titles like "jquery ajax redirect" but they all appear to involve accomplishing some other goal, rather than just directly checking the status that a server gives.
$. ajax({ type: 'POST', url: 'AJAX URL', data: "YOUR DATA" // don't forget to pass your csrf_token when using post success: function(data){ $("what_ever_you_want_to_replace"). html(data. view); }, error: function(xhr, type, exception) { // if ajax fails display error alert alert("ajax error response type "+type); } });
301 is an HTTP status code sent by a web server to a browser. A 301 signals a permanent redirect from one URL to another, meaning all users that request an old URL will be automatically sent to a new URL.
If you are using jquery you could look at the questions below to implement it. By default jQuery (and most libraries with Ajax) don't follow redirects by default:
How to manage a redirect request after a jQuery Ajax call
How to prevent ajax requests to follow redirects using jQuery
handle jquery ajax redirect
Maybe this answer is a little bit late but i had the same problem with 301 response on ajax request. The solution was quite simple:
apache rewrite rule is something like this:
RewriteRule ^([^/]\w+)/?$ index.php?%{QUERY_STRING} [L,E=MODULE:$1]
Your XHR-Request url looks someting like this:
/this/is/a/canonical/url + '?param=1¶m=2...'
It will lead to the 301 moved permanently if you dont use a direct file call (f.i. *.php) and rewrite to canonical URL (looks like a directory-path without f.i. *.php) instead.
To solve this problem just add a / to your XHR-Request-URL like this:
/this/is/a/canonical/url + '/' + '?param=1¶m=2...'
Maybe this will help someone.
I also had this problem and the suggestion about the trailing slash got me thinking ... I had a rewrite rule in my Web.Config to make everything lowercase and that's what was messing up my AJAX call. I was POSTing to GetResults (which showed up as a 301) and my rewriter (for some unknown reason?) was changing it to a lower-cased getresults GET which resulted in a 404.
Hope this might help someone else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With