Saving data in CakePHP, and posting JSON via AJAX simultaneously?

Go To StackoverFlow.com

1

So I have a form, AND I have a KnockoutJs app, with a CakePHP back end. When I hit Cake's default "save" button, I'm wanting to spit out and post a JSON along with the standard form data.

Here's what I have in my JS so far:

$('input.saveProgram').click(function() {
    var theJson = ko.mapping.toJSON(pvm, mapping);
    $.ajax({
        url: 'http://localhost/cake/programs/edit',
        dataType: 'json',
        type: 'POST',
        data: theJson
    });
});

In Cake, I'm trying to use the the Request handler in my controller, but to no avail:

if($this->RequestHandler->setContent('json', 'application/json')) {
    // standard saving code
}

In my Cake app I've tried die($this->request->data) to see what's going on and the JSON doesn't seem to be posting at all.

2012-04-04 03:41
by Benjamin Allison


0

Here's a solution as I interpret your question. In your controller:

    if($this->RequestHandler->isAjax()){

        // "spit" out json
        echo $this->data;

        //decode data into an array
        $decodedData = json_decode($this->data);        

        //standard saving code would 
        $this->Model->save($decodedData);
    }
2012-04-04 16:15
by Bryan Plasters
Ads