Baehr
Baehr

Reputation: 686

Retrieving POST data with CakePHP without formhelper

I'm trying to pass a POST variable to one of my controllers, however I'm doing this from a static page (I know, not the cleanest and most efficient way to go about things. But for the sake of learning...). How can I read that POST variable in my controller if the POST data is being sent without a FormHelper form?

I'm posting the data using jQuery ajax, so this is without the CakePHP native "FormHelper".

Does this make sense? Let me know if I need to elaborate. I appreciate any help you can provide :)

Upvotes: 5

Views: 12679

Answers (4)

cedric
cedric

Reputation: 11

For CakePHP 2.x it is

$this->request->data['ModelName']['field_name'];

or

$_POST['data']['ModelName']['field_name'];

The first option is recommended.

Upvotes: 0

Faisal
Faisal

Reputation: 4765

You should able to access form post data with:

For CakePHP 2.x

if ($this->request->is('post')) {
    pr($this->request->data);
}

For CakePHP 3.4.x

if ($this->request->is('post')) {
    pr($this->request->getData());
}

Please for further reference, read the manual. It's so much easier and better for yourself to figure it out by yourself.

Documentation for CakePHP 2.x

Documentation for CakePHP 3

Upvotes: 2

Ross
Ross

Reputation: 17977

Don't forget Cake is just PHP.

class BazController extends AppController {

    function foo() {
        $foo = $_POST['bar'];
        $this->set('foobar', $foo);
    }

}

is perfectly valid. But I would do as @dhofstet suggests as it's much more "cakey".

Upvotes: 6

dhofstet
dhofstet

Reputation: 9964

You should be able to access the data with:

$this->params['form']['YOUR_VARIABLE_NAME']

And if you follow the naming convention used by the FormHelper and name your input field like data[ModelName][FieldName], then you can access the data as usual with:

$this->data['ModelName']['FieldName']

Upvotes: 6

Related Questions