How to send cake php form by Ajax?

0

I would like to know how I can send a form via ajax to the controller of my view cabemensionar that I use cakephp:

Vista

<div class="usuarios form large-9 medium-8 columns content">
    <?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __('Add Usuario') ?></legend>
        <?php
            echo $this->Form->control('nombre');
            echo $this->Form->control('correo');
            echo $this->Form->control('contrasena');
            echo $this->Form->control('tipo');
            echo $this->Form->control('fecha_creacion');
            echo $this->Form->control('fecha_sesion');
        ?>
    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>
</div>

and the information that comes to my controller:

CONTROLLER

public function add()
    {
        $usuario = $this->Usuarios->newEntity();
        if ($this->request->is('post')) {
            $usuario = $this->Usuarios->patchEntity($usuario, $this->request->getData());
            if ($this->Usuarios->save($usuario)) {
                $this->Flash->success(__('The usuario has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The usuario could not be saved. Please, try again.'));
        }
        $this->set(compact('usuario'));
    }

I HOPE SOMEONE CAN HELP ME

    
asked by Jasi Enriquez 12.01.2018 в 01:25
source

1 answer

0

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

    
answered by 13.01.2018 в 00:28