Submit modal form using Ajax

my index.php

 
<div class="row">
    <div class="col-sm-12">
        <?php
            $flashMessage = $this->Flash->render();
            if ($flashMessage) {
                echo '<div class="clearfix"><p></p>' .$flashMessage . '<p></p></div>';
            }
        ?>
        <?php if ($this->Paginator->counter('{{count}}') == 0): ?>
            <div class="alert alert-info lead">
                <i class="fa fa-exclamation-circle"></i> No users yet!
            </div>

        <?php else: ?>
            <div class="panel panel-default">
                <table class="table table-responsive table-striped table-bordered ">
                    <thead>
                        <tr>
                            <th scope="col">S/N</th>
                            <th scope="col"> Name </th>
                        </tr>
                       <tr>
                        <td><?=$it ?>
                        <td> <?=$name  ?>
                       </tr>
                </table>
            </div>
<?php endif;  ?>

My Modal form

<div class="container">
    <h2>Modal Example</h2>
    <!-- Trigger the modal with a button -->
    <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
    <div class="modal fade" id="myModal" role="dialog">
            <div class="modal-dialog">
            
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Modal Header</h4>
                </div>
                <div class="modal-body">
            <div class="clearfix">
            <div class="col-sm-11">
            
                <?php
                    $flashMessage = $this->Flash->render();
                    if ($flashMessage) {
                        echo '<div class="clearfix"><p></p>' .$flashMessage . '<p></p></div>';
                    } 

            
                    // foreach ($error as  $value) {
                        $error=$this->Flash->render();
                    if ($flashMessage) {
                        echo '<div class="clearfix"><p></p>' . $error . '<p></p></div>';
                    }
                
                ?>
                <?php echo $this->Form->create($accUser, ['type' => 'post', 'class' => 'form-horizontal','id'=>'csFrom']); ?>

                        <div class="form large-9 medium-8 columns content">
                        
                                <div class="panel panel-default">
                                    <div class="panel-body">

                                    <div class="form-group">
                                            <label for="Name" class="col-sm-3 control-label">First Name</label>
                                            <div class="col-sm-9"> 
                                                <?php
                                                    echo $this->Form->input('FName', [
                                                        'label' => false,
                                                        'id' => 'FName',
                                                        'class' => 'form-control',
                                                        'empty' => 'Select group',
                                                        'type' =>'text',
                                                        'required' => true, 
                                                    ]);
                                                ?>
                                            </div>
                                        </div>

                                    <div class="form-group">
                                            <label for="BeginDate" class="col-sm-3 control-label">Begin Date</label>
                                            <div class="col-sm-9">
                                                <?php
                                                    echo $this->Form->input('BeginDate', [
                                                        'label' => false,
                                                        'id' => 'BeginDate',
                                                        'class' => 'form-control',
                                                        'type' => 'date',
                                                        'minYear' => date('Y'),
                                                        'maxYear' => date('Y') + 1,
                                                        'required' => true,
                                                    ]);
                                                ?>
                                            </div>
                                        </div>
                                    
                                    <div class="form-group">
                                            <label for="EndDate" class="col-sm-3 control-label">End Date</label>
                                            <div class="col-sm-9">
                                                <?php
                                                    echo $this->Form->input('EndDate', [
                                                        'label' => false,
                                                        'id' => 'EndDate',
                                                        'class' => 'form-control',
                                                        'type' => 'date',
                                                        'minYear' => date('Y'),
                                                        'maxYear' => date('Y') + 1,
                                                        'required' => true,
                                                    ]);
                                                ?>
                                            </div>
                                        </div> 
                             
                        <div class="panel-footer text-center">
                                <button type="submit" class="btn btn-success" id="submit_add"><?php echo  'SUBMIT' ?></button>
                            </div>
                        </div>
                <?php echo $this->Form->end(); ?>
            </div>
        </div>

            </div>
            <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
        
        </div>
    </div>
  
</div>

<script>

    $('#csFrom').submit(function (event) { 
        event.preventDefault() 
        
        $.ajax({
                type:'POST',
                async: false,
                cache: false, 
                url: '<?= $this->url->build(["prefix"=>"Admin","controller" => "Users", "action" => "ajaxadd"]); ?>',
                headers:{
                    'X-Csrf-Token':$('meta[name="csrfToken"]').attr('content')
                }, 
                //dataType: 'json',
            data: $('csFrom').serialize(),
            beforeSend: function(xhr) {
               xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrfToken"]').attr('content'));
            },

            // contentType: "application/json",
            success: function(response) { 
                //success   
                console.log(response);                
                if (response == true){
                    console.log(response); 
                    location.reload()
                }             
            },
            error: function(error, message) {
                console.log(error, message);
            }
        });
            
    });
</script> 


Controller
 public function ajaxadd(){
       $data= $this->request->getData('id');
        echo json_encode($data);
    }

Error:

http://test/admin/users/ajaxadd 400 (Bad Request)
Submit is not reaching action of the controller.

What I have done sometimes:

  1. Added <?= $this->Html->meta('csrfToken', $this->request->getAttribute('csrfToken'))?>
    to default Layout
  2. Set $this->Security->setConfig(‘unlockedActions’, [‘ajaxadd’]); off in controller

are you tring to insert to database?

Yes, I am trying to do a post submission to database.

$(‘#form’).submit(function (e) {
e.preventDefault();
var data = new FormData(this);
$.ajax({
url: ‘Your URL here’,
type: ‘POST’,
method: ‘POST’,
data: data,
processData: false,
contentType: false,
cache: false,
dataType: ‘JSON’,
beforeSend: function (e) {

        },
    }).done(function (data, status, xhr) {
    
    }).fail(function (data, status, xhr) {
   
    });
});

// In Controller

$employment = $this->Employments->newEmptyEntity();
if ($this->request->is(‘post’)) {
$employment = $this->Employments->patchEntity($employment, $this->request->getData());

        if ($this->Employments->save($employment)) {
            $result = ['message' => ucwords('The employment has been saved'), 'result' => ucwords('success'))];
            return $this->response->withStatus(200)->withType('application/json')
                ->withStringBody(json_encode($result));
        }else{
            foreach ($employment->getErrors() as $key => $value){
                $result = ['message' => ucwords(reset($value)), 'result' => ucwords('error'),
                    'errors' => $employment->getErrors()];
                return $this->response->withStatus(422)->withType('application/json')
                    ->withStringBody(json_encode($result));
            }
        }
    }

This is only a sample, use logic for the rest