Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent jQuery ajax from following a redirect after a post?

I have a link which dispatches an Ajax POST to perform an action. If the user is not yet signed in, the action method returns a 302 redirect to the login page. If this happens, I want to catch the redirect, so that I can display the login form in a lightbox.

However, it seems that jQuery follows the redirect without returning control or calling a callback function. In the code below, the alert of 302 redirect is never called, and by the time the dataFiler function is called, the data is the content of the login page.

How can I see that the page has sent a 302 redirect, and branch to a different action?

 $.ajax(url,
        {
            data: postArguments,
            type : "POST",
            success: function (data) { alert(' success function'); },
            statusCode:
            {
                302: function () { alert(' received redirect 302'); },
                301: function () { alert(' received redirect 301'); }
            },
            dataFilter: function (data, type) { alert('got data ' + data); return data; }
        });
like image 535
Mike Kantor Avatar asked Apr 04 '12 15:04

Mike Kantor


People also ask

How do I stop Ajax from redirecting?

Your answer Hii kartik, You can resolved this issue like this: Add a middleware to process response, if it is a redirect for an ajax request, change the response to a normal response with the redirect url. Then in ajaxComplete, if the response contains redirect, it must be a redirect, so change the browser's location.

Does jQuery Ajax follow redirect?

jQuery's $. 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.

How do I stop a redirect in Javascript?

If it's only redirects through link clicks, in jQuery you can do this: $(". someClass a"). unbind('click');

How AJAX works behind the scenes?

AJAX comprises a set of useful web development techniques utilized to develop dynamic and speedy web pages. Behind the scenes, it shares small chunks of the data, permitting the web pages to be updated asynchronously. This states that by using AJAX, HTML page elements will be updated without reloading.


1 Answers

This is not a limitation with jQuery but with JavaScript itself; there is no way to detect a redirect in an AJAX request in JavaScript; the browser XHR objects auto-magically and invisibly follow redirects as per the spec.

The ideal option would be to add a catch in your server code to detect an AJAX request ("HTTP_X_REQUESTED_WITH" header), and return a special response to detect an anonymous user in your JavaScript, and handle appropriately.

like image 68
Matt Avatar answered Sep 18 '22 11:09

Matt