I'm trying to return a http response with a 402 status code and a JSON content, it's ok, but the problem happens when I try to read this response body using the JQuery.parseJSON(json).
$response = new \Zend\Http\Response();
$response->setStatusCode(402);
$response->setContent(json_encode([
"success" => false,
"message" => "You need to buy more credits"
]));
return $response;
Then I try to read the response content:
search: function(term, callback){
$.post("/api/v1/client/search", {term: term}).always(function(data){
callback(jQuery.parseJSON(data));
});
},
And I got the following error: "Uncaught SyntaxError: Unexpected token o". When I use the 200 status code everything goes ok, but when I change it to 402 I get this problem.
I don't know if it happens because the browser don't deliver the reponse body assuming the status code as the response itself, but this does not change the fact that the server has sent the message.
Is there a way a can read it? Have I done some mistake?
Thanks.
I've soved the problem. I hava detected that the object returned by jQuery changes when I change my status header in PHP. When the status code is 200, jQuery returns a string, when status code is 402, jQuery returns a object, and the text I was looking for is the "responseText" property of this object.
https://i.sstatic.net/Ziqtl.png
My solution was:
search: function(term, callback){
$.post("/api/v1/client/search", {term: term}, function(data){
callback(JSON.parse(data));
})
.fail(function(data){
callback(JSON.parse(data.responseText));
});
},