If you want to create forms by javascript, I would recommend you to use a framework like VueJs, angular or the React library, and use the amazing CakePHP to generate the Apis of the controllers of your database models.
If you want to use Jquery it's more cumbersome, but obviously possible:
input to the controller to send things by ajax you would have to disable the security component of the form:
public function beforeFilter(Event $event)
{
$this->Security->setConfig('unlockedActions', ['add', 'edit', 'delete']); // o los que te hagas
}
and then put the ajax code:
$(document).ready(function() {
// Al clicar ek submit
$('form').submit(function(event) {
// metes en una variable los datos de formulario, ojo tiene que estar igual de como los llamaste para hacer el CRUD en cakephp
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'superheroAlias' : $('input[name=superheroAlias]').val()
};
// process the form
$.ajax({
type : 'POST', // define el tipo de metodo
url : '/usuarios/add', // la url de tru controlador y acción
data : formData, // el objeto
dataType : 'json', // de tipo json
encode : true
})
// usas una promesa de callback
.done(function(data) {
// y miras q se mandan bien los datos
console.log(data);
//
});
event.preventDefault();
});
});
Very important, in fact the most important thing is to be able to send json fomulares.
link
// src/Controller/RecipesController.php
class UsuariosController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
public function index()
{
$usuarios = $this->Usuarios->find('all');
$this->set([
'usuarios' => $usuarios,
'_serialize' => ['usuarios']
]);
}
public function view($id)
{
$usuario = $this->Usuarios->get($id);
$this->set([
'usuario' => $usuario,
'_serialize' => ['usuario']
]);
}
public function add()
{
$recipe = $this->Usuarios->newEntity($this->request->getData());
if ($this->Usuarios->save($recipe)) {
$message = 'Saved';
} else {
$message = 'Error';
}
$this->set([
'message' => $message,
'recipe' => $usuario,
'_serialize' => ['message', 'usuario']
]);
}
public function edit($id)
{
$recipe = $this->Usuarios->get($id);
if ($this->request->is(['post', 'put'])) {
$recipe = $this->Usuarios->patchEntity($recipe, $this->request->getData());
if ($this->Usuarios->save($recipe)) {
$message = 'Saved';
} else {
$message = 'Error';
}
}
$this->set([
'message' => $message,
'_serialize' => ['message']
]);
}
public function delete($id)
{
$recipe = $this->Usuarios->get($id);
$message = 'Deleted';
if (!$this->Usuarios->delete($recipe)) {
$message = 'Error';
}
$this->set([
'message' => $message,
'_serialize' => ['message']
]);
}
}
And the routas clear:
link
Router::scope('/', function ($routes) {
// Prior to 3.5.0 use 'extensions()'
$routes->setExtensions(['json', 'xml']);
});
For more info:
this is very good:
link