POST data from knockout.js to CakePHP controller

2019-08-07 08:14发布

问题:

I'm posting data from a knockout.js page to a controller in cakephp and it says the data was successfully posted, however, my controller doesn't seem to be responding and I don't get an alert back...not even a null response. I even checked the network tab in chrome and it shows the correct data being POSTED

Here's the data being posted from my knockout viewmodel file

var JSON_order = JSON.stringify({"orderInfo":[{"itemNumber":"1","quantity":"1","price":1.00,"productName":"test"}]});
$.post("/orders/submit_order", JSON_order,
function(data){
    alert(data.check); //alert doesn't appear
}, "json");

Here's my controller

function submit_order(){
    $this->layout = false;
    $this->autoRender = false;
    if ($this->request->is('post')) {
        $order = $this->request->data;
        $order = json_decode($order, true);
        $finalize_order = new submit;
        $finalize_order->display_submitted_order_success($order);
    }
}

Here's the code for display_submitted_order_success (I also tried this on a php file outside of CakePHP but it didn't work either)

function display_submitted_order_success($order = null){
    $this->layout = false;
    $this->autoRender = false;
      //I'm just trying to display the order as-is so that I know it's even being posted to begin with
    echo json_encode(array("check" => "success","order_num" => $order)); //the values passed the price check, display the result 
}

回答1:

You have to assign the value of JSON_order to a var:

var JSON_order = JSON.stringify({"orderInfo":[{"itemNumber":"1","quantity":"1","price":1.00,"productName":"test"}]});
$.post("/orders/submit_order", {order:JSON_order},
function(data){
    alert(data.check); //alert doesn't appear
}, "json");

So that your controller would receive it like this:

$data['order'] = '{"orderInfo":[{"itemNumber":"1","quantity":"1","price":1,"productName":"test"}]}'