y1jewg
Last Updated: January 28, 2019
·
5.772K
· my3recipes

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.

4 Responses
Add your response

30699

We can understand well to get the free fifa 19 coins here. http://fewcheats.com/fifa-19/

5 months ago ·
30836
5 months ago ·
31125

One of the main and major problems 0cii4O.sys occurs in computers that is create some issue, if you want to avoid then you can download new version file with the help of https://unfitpc.com/0cii4O-sys it becomes more helpful for you.

3 months ago ·
31514

https://musicallyfanspremium.info
tiktok fans free,tiktok generator 2019,tiktok hearts hack

29 days ago ·