I am having a ajax post call to a cakePhp Controller:
$.ajax({
type: \"POST\",
url: \'locations/add\',
data: {
there are few things to return JSON
response:
RequestHandler
componentjson
_serialize
valuefor example you can move first 3 steps to some method in parent controller class:
protected function setJsonResponse(){
$this->loadComponent('RequestHandler');
$this->RequestHandler->renderAs($this, 'json');
$this->response->type('application/json');
}
later in your controller you should call that method, and set required data;
if ($this->request->is('post')) {
$location = $this->Locations->patchEntity($location, $this->request->data);
$success = $this->Locations->save($location);
$result = [ 'result' => $success ? 'success' : 'error' ];
$this->setJsonResponse();
$this->set(['result' => $result, '_serialize' => 'result']);
}
also it looks like you should also check for request->is('ajax)
; I'm not sure about returning json
in case of GET
request, so setJsonResponse
method is called within if-post
block;
in your ajax-call success handler you should check result
field value:
success: function (response) {
if(response.result == "success") {
console.log('success');
}
else if(response.result === "error") {
console.log('error');
}
}