I am trying to send an ajax request from a javascript file to a cakephp controller. Ajax sends a simple json object (for simplicity, I hard-coded it in this example).
When I log the server, the server can decode the json string into an object. The function $this->Votes->delete
is called successfully. My problem is that everything works as it should, but I still get the error message.
Below is my code, and below is the result that I get from it.
JavaScript:
function unvote() {
$.ajax({
type: 'POST',
url: '../votes/unvote',
async: false,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({'post_id':1}),
success: function(data, textStatus, jqXHR){
console.log(data);
console.log(textStatus);
console.log(jqXHR);
}.
error: function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},
});
}
PHP: Voice Controller
public function unvote(){
$this->autoRender = false;
$vote = $this->Votes->newEntity();
if ( $this->request->is('ajax') ) {
$data = $this->request->input('json_decode');
$vote =
if ( $this->Votes->delete($vote) ) {
$this->response->body('Success');
$this->response->statusCode(200);
} else {
$this->response->body('Failure');
$this->response->statusCode(500);
}
}
$this->response->type('json');
return $this->response;
}
ajax Response:
Object{ readyState=4, responseText="", status=200, statusText="Ok", more...}
parsererror
SyntaxError:JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
> return window.JSON.parse( data + "" );
source
share