Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX GET/POST request returns 404 in error handler, but valid response is sent from server

The Problem: I send GET or POST request with jQuery.ajax and get an error handler triggered with 404. The thing is, I have used a sniffer to check an answer from server and it is a valid 200 response with a correct JSON (returned by Python json.dumps). And something weird: after this call ends up with 404 a browser reloads the page.

Everything lives in the same domain (and subdomain too).

jQuery call:

$.ajax({type: "POST", url: "/m/auth/login", data: {x: "y"},
success: function(result) {}, error: function(xhr) {}, dataType: "json"});

Response as seen by sniffer with payload decompressed:

HTTP/1.1 200 OK\r\n
Content-Type: text/html; charset=utf-8\r\n
Cache-Control: no-cache, must-revalidate\r\n
Content-Encoding: gzip\r\n
X-AppEngine-Estimated-CPM-US-Dollars: $0.000018\r\n
X-AppEngine-Resource-Usage: ms=71 cpu_ms=0\r\n
Vary: Accept-Encoding\r\n
Date: Tue, 24 Dec 2013 21:04:36 GMT\r\n
Pragma: no-cache\r\n
Expires: Fri, 01 Jan 1990 00:00:00 GMT\r\n
Server: Google Frontend\r\n
Content-Length: 80\r\n
Alternate-Protocol: 80:quic,80:quic\r\n
\r\n
{"reason": {"password": "missing", "email": "missing"}, "error": "argument"}
like image 267
Artaxerxes Avatar asked Nov 02 '22 08:11

Artaxerxes


1 Answers

the server response with content-type: text\html and your ajax call expects json. you'll need to set the header of the response to Content-type: application/json. also you might try setting the headers of your ajax call to accept gzip encoded data.

in php you could do this

header('Content-type: application/json');

before you echo the json. Or you could set the type of the ajax call to text, html.

also it is recommended to chain your callback functions with jquery like so

$.ajax({
    url: '/m/auth/login',
    headers: { "Accept-Encoding" : "gzip" },
    type: 'POST',
    dataType: 'json',//be sure you are receiving a valid json response or you'll get an error
    data: {x: 'y'},
})
.done(function(response) {
    console.log("success");
    console.log(response);
})
.fail(function() {
    console.log("error");
})
.always(function() {
    console.log("complete");
});
like image 71
kasper Taeymans Avatar answered Nov 12 '22 17:11

kasper Taeymans