Search code examples
cakephpjqueryjquery-post

Cakephp empty $this->data after $.post submit through jquery


I want to pass data to my ajax function in the controller, however the $this->data is empty.

I have in the JS:

$.post('/teach/update_word', {one: '1', two: '2'}, function (data){
    alert(data);
});

And in the Controller:

function update_word(){ // AJAX
    $output;
    if($this->data){
        $output['data']= 'yes';
    }else{
        $output['data']= 'no';
    }
    echo json_encode($output);
    die();
}

My function always returns {"data":"no"}.


Solution

  • Only data that comes from (or looks like it is coming from) forms created by CakePHP's FormHelper end up in $this->data, so you would need to use fields names like data[Word][one].

    For all other data you would usually find in $_POST, you need to look in $this->params['form']; (or $this->params['url'] for $_GET).