Reputation: 171
I'm trying to AJAXify an old website form without modifying the back end. Originally, the backend would response with a "302 Moved" redirect to a "thank you" page after receiving the form.
Now, when I try to submit the form using a jQuery $.ajax call, the form data gets submitted successfully, but the "302 Moved" redirect seems to get cancelled by the browser and jQuery doesn't know what's going on.
My problem is that no matter what happens, the $.ajax call returns with an error and status = 0, so I have no way to distinguish between a successful submit and an error.
Is there a way to prevent the browser from trying to follow the redirect, or at least getting back the proper response codes? (I'm using Chrome.)
Upvotes: 17
Views: 26122
Reputation: 25
Check the form an add {{csrf_field()}}.it is caused when the form get submitted without the token.
Upvotes: 0
Reputation: 1
The Ajax code would look like this:
$.ajax({
'url': '/your-url',
'method': 'post',
'data': form.serialize()
}).done(function(data) {
// something
}).fail(function(jqXHR, textStatus, errorThrown) {
if (jqXHR.getResponseHeader('Location') != null)
{
window.Location= jqXHR.getResponseHeader('Location');
}
// other conditions in failure situation.
});
Upvotes: 0
Reputation: 1387
Your backend app propably has relative redirect which may somehow be not processed by jquery ajax. Location header will not include domain name in this situation, just relative path. For some (unclear for me ;)) reasons it may cause same origin policy issues. What is funny, changing redirect to absolute path should fix the issue. Tested on jQuery 1.11.1.
Theoretical ajax call:
$.ajax({
'url': '/your-url',
'method': 'post',
'data': form.serialize()
}).done(function(data) {
// something
}).fail(function(jqXHR, textStatus, errorThrown) {
// another something
});
So in /your-url controller you may have something similar to:
return $this->response->redirect('//same.domain/path');
or
return $this->response->redirect('/path');
First one wil work. Second one not.
The point is that you propably need to change backend but only a little bit. You don't need to check is the request a XmlHttpRequest if you really don't want to and/or handle it in different way.
Upvotes: 0
Reputation: 2865
I think no,you can't do it without changing the back-end.You have to change the response header,for Ajax to know/understand what to do.If you made a redirect,you have to change the header,because Ajax call response will not do it.
Upvotes: 1
Reputation: 61
Could this get you in the right direction?
$.ajax({
type: "GET",
url: url,
data: data,
complete: function(e, xhr, settings){
if(e.status === 200){
console.log(e.responseText);
}else{
console.log("error");
}
}
});
Upvotes: 0