On Mon, Jan 11, 2010 at 10:50 PM, Dave <make.cake.b...@gmail.com> wrote:
> Does anyone know how to return a JSON object from an ajax request to return
> the view and a success status? I see all these tutorials to retrn data but
> no html. Everything is layout = false, autoRender = false. I can return the
> view in normal html but I need to get a status = true or false to the js to
> tell it what to do next depending on the status. I need to update 1 of 2
> possible divs with the response and that's why I need the success to tell
> the js if success update this div if no success then do something different.
>
> I need to return a view along with my success or fail status. Not just an
> error message as I have found in my json / cakephp searching.
>
> so in the controller
> $this->layout = 'ajax';
> if(this->Model->save())
> {
> //return success = true and success view
> $respounse = array('status' => true, 'html' => ???
>
>
> } else {
>
>  //return false
>  $respounse = array('status' => false);
> }
> $this->header('Content-Type: application/json');
>        echo json_encode($response);
>
>
>
>
>
>
> Ideas?

My approach is:
1. create json layout in views/layout/json/default.ctp which contains:
<?php
header("Pragma: no-cache");
header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
header('Content-Type: application/json');

echo $content_for_layout;
?>

2. create common view for json, says app/views/common/jsonize.ctp --
my controllers use this oftenly, which contains:
<?php echo $javascript->object($result); ?>

3. I put jsonize in app_controller.php, so other controllers will benefit this:
function jsonize() {
    $this->layout = 'json/default';
    $this->viewPath = "common";

    if ( Configure::read('debug') > 0 ) {
        Configure::write('debug', 0);
    }

    if ( !$this->params['named'] ) {
        $this->Session->setFlash('Invalid parameter for JSON', 'error');
        $this->redirect(array('action'=>'index'));
    }

    foreach ($this->params['named'] as $field => $value) {
        $like = str_replace('*', '%', $value);
        $condition[Inflector::singularize($this->name).".$field LIKE"] = $like;
    }
    $this->{Inflector::singularize($this->name)}->recursive = -1;
    $result = $this->{Inflector::singularize($this->name)}->find('all',
array( 'conditions' => $condition ));
    $this->set('result', $result);
}

It just a little modification is you used on $this->Model->save()


-- 
regards,
gedex

blog: http://gedex.web.id

Check out the new CakePHP Questions site http://cakeqs.org and help others with 
their CakePHP related questions.

You received this message because you are subscribed to the Google Groups 
"CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to
cake-php+unsubscr...@googlegroups.com For more options, visit this group at 
http://groups.google.com/group/cake-php?hl=en

Reply via email to