As JsHelper is no more in cakephp 3.0 so what i am doing is to save my form data into database using ajax
$this->Form->create('Employees'); $this->Form->input('name', array('id'=>'name')); $this->Form->input('age', array('id'=>'age')); $this->Form->button('Add Info', array( 'type'=>'button', 'onclick'=>'infoAdd();' )); $this->Form->end();
js.js
function infoAdd() { var name=$("#name").val(); var age=$("#age").val(); $.get('/employees/info?name='+name+"&age="+age, function(d) { alert(d); }); }
EmployeesController.php
class EmployeesController extends AppController {
public $components=array('RequestHandler');
public function add() {
$emp=$this->Employees->newEntity();
if($this->request->is('ajax')) {
$this->autoRender=false;
$this->request->data['name']=$this->request->query['name'];
$this->request->data['age']=$this->request->query['age'];
$emp=$this->Employees->patchEntity($emp,$this->request->data);
if($result=$this->Employees->save($emp)) {
echo "Success: data saved";
//echo $result->id;
}
else {
echo "Error: some error";
//print_r($emp);
}
}
}
}
not empty
rule for both fieldsTake away the autoRender line and serialize the data you want returned:
public function add() {
$data = [];
$emp=$this->Employees->newEntity();
if($this->request->is('ajax')) {
$this->request->data['name']=$this->request->query['name'];
$this->request->data['age']=$this->request->query['age'];
$emp=$this->Employees->patchEntity($emp,$this->request->data);
if($result=$this->Employees->save($emp)) {
$data['response'] = "Success: data saved";
//echo $result->id;
}
else {
$data['response'] = "Error: some error";
//print_r($emp);
}
}
$this->set(compact('data'));
$this->set('_serialize', 'data');
}
The serialize function tells Cake that it's not expecting the function to have a view, so autoRender is not needed (http://book.cakephp.org/3.0/en/views/json-and-xml-views.html).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With