Reputation: 564
I'm using jQuery 1.6.2 to make a POST AJAX request to a page on the same domain. That page does a 302 redirect to another page.
Now, on my local machine this work fine but on our production server, the redirect is never followed and in the Chrome inspector the request is said to be 'canceled'.
If I visit the same page without involving javascript, everything works fine, and as I said the AJAX works on my local machine but not on the production server.
Does anyone know what might cause this?
There are some differences between the servers (OS X, Apache2, PHP5.3.6, HTTP on local machine, Ubuntu, Lighttpd, PHP5.3.3, HTTPS on production) but none that to me should make any difference.
Upvotes: 24
Views: 64107
Reputation: 9739
I consider this to be a server-side issue, and not client-side. The browser is correct not to follow redirections to http
when it makes ajax request by https
, as that would be a security flaw.
I realized I was using relative paths, such as HttpResponseRedirect('/path/to/')
. On some layer, that url was prepended with the http://
prefix and that was what the browser received: http://example.com/path/to/
You must ensure that the Location
gets sent in the response header with a full path, including the https://
.
Upvotes: 3
Reputation: 24292
function doAjaxCall() {
$.ajaxSetup({complete: onRequestCompleted});
$.get(yourUrl,yourData,yourCallback);
}
function onRequestCompleted(xhr,textStatus) {
if (xhr.status == 302) {
location.href = xhr.getResponseHeader("Location");
}
}
following questions related to your answer. you can find the answer from below links.
Catching 302 FOUND in JavaScript
How to manage a redirect request after a jQuery Ajax call
Upvotes: 5
Reputation: 5818
Based on this answer: https://stackoverflow.com/a/8752354/698289 I found the following code to be very useful:
$('body').ajaxComplete(function (e, xhr, settings) {
if (xhr.status == 200) {
var redirect = null;
try {
redirect = $.parseJSON(xhr.responseText).redirect;
if (redirect) {
window.location.href = redirect;
}
} catch (e) {
return;
}
}
});
Then you just provide JSON such as the following:
{redirect: '/redirect/to/this/path'}
And the ajaxComplete
will make sure to redirect the browser.
Be mindful that $.ajax('complete')
triggers AFTER $.ajax('success')
or $.ajax('error')
Upvotes: 2
Reputation: 564
Turns out a bug in the redirect code caused the redirect to go to http:// while the page that was requested was https://. That makes the browser refuse to follow the redirect.
Upvotes: 14