Skip to content
Advertisement

CakePHP4 – Create Record with Ajax

I’m new working with CakePHP and I’m having a hell of a time trying to figure out how to add a form that can post to a different db table with ajax. Basically, I’ve got a form that carries out a search which works fine, but before the user carries out the search I need to capture his email & some other fields and store them in a separate table in my db.

While I’ve been able to set up a form and send the data to the controller, I can’t get past an error 400 / bad request. I’m not sure if it’s because I’ve got the post url set up wrong (having enabled: $this->loadComponent(‘FormProtection’);

Any help or orientation would be greatly appreciated!! I haven’t been able to figure this out, maybe I’m approaching the problem wrong or I should use a post link (if that’s even possible).

The setup that I’ve currently got:

index.php => website.com/app/services:

<div id="user_basics"> 
<?= $this->Form->create() ?>
<fieldset>
    <legend><?= __('Add Visitor') ?></legend>
    <?php
        echo $this->Form->control('name');
        echo $this->Form->control('email');
        echo $this->Form->control('city');
    ?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>

jQuery: 
$('#user_basics form').submit(function(event) {
    
var ajaxdata = $("#user_basics form").serializeArray();

event.preventDefault();

    $.ajax({
        url:"<?= $this->Url->build(["controller" => "visitors","action" => "addExternal"]); ?>",
        type:"POST",
        headers: $('[name="_csrfToken"]').val(),
        data:ajaxdata,
        dataType: "json",
        success:function(response) {
            console.log(response);
            console.log("success");
        },
        error: function(response) {
            console.error(response.message, response.title);
            console.log("nope");
        }
    });

});

I haven’t included the controller file with the addExternal action.

Note: I’m pointing to visitor controller, I believe that’s the right way to go about this – sending the users’ data to the visitor controller which is already setup to connect to the db)

Advertisement

Answer

A simple mistake

var ajaxdata = $("#user_basics form").serializeArray();

You are trying to Serialize array from a form which have”user_basics form”. Here id “user_basic” may have multiple form. so it’s best idea to create the form with id

<?= $this->Form->create(null,[
           'id'=>'user_basic_form',
    ]) ?>
var ajaxdata = $("#user_basic_form").serializeArray();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement