Respond to ajax call with json message and status code (CakePHP)
If you’re working with CakePHP and building a single-page application (SPA), REST API or just an ajax request - there are cases when you need to respond to client that request was rejected (auth fails, no such action & etc). With regular requests, it’s simple like this:
if (...) {
throw new NotFoundException('Could not find that post');
}
or just use Session setFlash function. But what about ajax calls? You want to respond as HTTP status code with message? This way won’t work. You need to set respond as json, status code and halt whole app:
if( ... ) {
if($this->request->is('ajax')) {
$this->response->type('json');
$this->response->statusCode(400);
$this->response->body(json_encode(
array('status' => 'ERROR', 'message' => 'Bad Request')));
$this->response->send();
$this->_stop();
}
}
Last line is optional:
$this->_stop();
This will halt whole application. In some cases you need it, for example unauthorized access:
public function isAuthorized($user) {
if( ... ) {
// Auth fails
if($this->request->is('ajax')) {
$this->response->type('json');
$this->response->statusCode(401);
$this->response->body(json_encode(
array('status' => 'ERROR', 'message' => 'Unauthorized')));
$this->response->send();
$this->_stop();
}
}
}
but there can be cases when you want to process your app further without stopping it.
Written by Mindaugas
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#