Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple ajax form in cakephp 3.0

As JsHelper is no more in cakephp 3.0 so what i am doing is to save my form data into database using ajax


i just have two input fields.
my files are:
  1. add.ctp
  2. js.js
  3. EmployeesController.php


add.ctp

    $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);
            }
        }
    }
}


Note : my model only have not empty rule for both fields

all what i am doing is working fine but i dont think i m doing it in right way or as it should be.
please help me what i m missing and what i don't need to do.
like image 870
Abar Choudhary Avatar asked May 04 '15 07:05

Abar Choudhary


1 Answers

Take 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).

like image 170
Isaac Askew Avatar answered Sep 28 '22 06:09

Isaac Askew