Sunday, December 29, 2013

How to respond based on request method?

Trying to sort this out but not getting anywhere.

 

I need to respond based on how the request was made.

 

So first I need to know if the data was saved:

 

$saved = $this->User->save($this->Controller->request->data, true, $forceFields);

Then return the saved / error message back to the user.

 

But then it gets messy and just looks wrong. Has to be a correct was as this clearly is not it. (ajax response gets sent back as a JSON response)

 

SNIP FROM COMPONENT IN A PLUGIN (but gives you an idea)

 

if ($saved && !$this->Controller->request->is('ajax')) {

                                                               

                $this->Session->setFlash(__('Good stuff saved via HTTP request.'));

                                                               

} else {

                                                               

                $this->Session->setFlash(__('Nope via HTTP.'));

                $this->Controller->redirect(array('action' => 'index'));

}

                                               

                                               

if ($saved && $this->Controller->request->is('ajax')) {

                                                               

                $response = array(

                                'status' => true,

                                'clear' => true,

                                'message' => 'Good stuff saved via ajax.');

                                                               

} else {

 

                $response = array(

                                'clear' => false,,

                                'message' => 'Nope via ajax.');

}

 

Thanks,

Dave

No comments: