Simple ajax form in cakephp 3.0

Since JsHelper is no longer used in cakephp 3.0, so I do this to save my form data in a database using ajax


I have only two input fields.
my files:
  • add.ctp
  • js.js
  • 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 has a not empty rule for both fields.

everything that I do works fine, but I don’t think I'm doing it right or how it should be.
please help me what I am missing and what I do not need to do.
+6
source share
1 answer

Remove the line autoRender and serialize the data you want to return:

 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 serialization function tells Cake that it does not expect the function to have a view, so autoRender is not required ( http://book.cakephp.org/3.0/en/views/json-and-xml-views.html ).

+6
source

Source: https://habr.com/ru/post/986480/


All Articles