Category: Javascript

Q: CakePHP 3 how to AJAX submit form post data to API?

I have an email subscribe form on homepage, and I may like to use AJAX submit form data to an API endpoint instead of http post redirect. I have write a new action ApiController/userSubscribe():

public function userSubscribe() {

    if ($this->request->is('ajax') && filter_var($this->request->data['email'], FILTER_VALIDATE_EMAIL)) 
    {

        $entity = $subscriptions->newEntity($this->request->data);
        if ($subscriptions->save($entity)) 
        {
            
            echo json_encode(['status' => 'ok']);
        } else {

            echo json_encode(['status' => 'error']);
        }
    } else 
    {
        echo json_encode(['status' => 'error_email']);
    }
}

index.ctp view:

<!-- ////Subscribe form//// -->
<?= $this->Form->create(null, array('type' => 'post', 'url' => ['controller' => 'api', 'action' => 'userSubscribe'], 'id' => 'submit-form', 'class' => 'sub-form vertical')); ?>


<?= $this->Form->input('name', array('type' => 'text', 'required' => true, 'placeholder' => '', 'label' => false, 'class' => 'w-input input-form', 'id' => 'name-field')); ?>
<?= $this->Form->input('email', array('type' => 'email', 'required' => true, 'placeholder' => '', 'label' => false, 'class' => 'w-input input-form', 'id' => 'email-field')); ?>

<?= $this->Form->end(); ?>

<button class="bn-large" id="bn_subscribe">Subscribe to News Letter</button>

<script type="text/javascript>
$('#bn_subscribe').click(function() {

    $.ajax({
        type: "POST",
        url: '/api/userSubscribe',
        data: $('#submit-form').serialize()
    });
});
</script>

But this is not working, I can't even get an error. Can anyone help me?

Thank you

ajax
1 Answers

Version: 3

I think it's the url problem.

use Cake\Routing\Router;
<script type="text/javascript">
$('#bn_subscribe').click(function() {

    $.ajax({
        type: "POST",
        url: '<?= Router::url(['controller' => 'api', 'action' => 'userSubscribe']) ?>',
        data: $('#submit-form').serialize()
    });
});
</script>
Kristi
Kristi

137