Skip to content
Advertisement

ERROR: POST http://localhost:8765/users/delete/delete8 403 (Forbidden)

I’m using cakephp4. trying to add some sweetalert. Sweetalert is popping up when the delete button is clicked but when I click confirm for delete it’s not deleting the data.

template/layout/Users/index.php

<table>
<tr>
    <th>Username</th>
    <th>Usertype</th>
    <th>Created</th>
    <th>Action</th>
</tr>

<?php foreach ($users as $user) : ?>
    <tr>
        <td>
            <?= $this->Html->link($user->username, ['action' => 'view', $user->slug]); ?>
        </td>
        <td>
            <?= $this->Html->tag('span', $user->utype) ?>
        </td>
        <td>
            <?= $user->created->format(DATE_RFC850); ?>
        </td>
        <td>
            <?= $this->Html->link('Edit', ['action' => 'edit', $user- 
               >slug]); ?> /
            
            <a href="#" class="delete" data-slug="<?=$user->slug? 
               >">Delete</a>
           
        </td>
    </tr>
<?php endforeach; ?>

template/layout/Users/index.php

<script>

deletes = document.getElementsByClassName('delete');
Array.from(deletes).forEach((element) => {
  element.addEventListener("click", (e) => {
    let ajax_url = $(e.target).attr('data-slug');
    
    Swal.fire({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
      if (result.isConfirmed) {
          $.ajax({
            method: 'POST',
            url: '/users/delete/'+ ajax_url,
            beforeSend: function(xhr){
                xhr.setRequestHeader(
                    'X-CSRF-Token',
                    <?= json_encode($this->request- 
                       >getParam('_csrfToken')); ?>
                );
            },
            success: function(response){
                if(response){
                    Swal.fire(
                        'Deleted!',
                        'Your file has been deleted.',
                        'success'
                    )
                }
                else {
                    Swal.fire({
                      icon: 'error',
                      title: 'Oops...',
                      text: 'No data deleted',
                 })
      }
            },
            error: function(e){
                console.log('error', e);
            }
          })
       
      } 
    })
  })
})

delete method is as follows in my UsersController.php

UsersController.php

public function delete($slug)
{
    $this->request->allowMethod(['post', 'delete']);
    $user = $this->Users->findBySlug($slug)->firstorFail();
    if ($this->Users->delete($user)) {
        $this->Flash->success("Deleted Successfully");
        return $this->redirect(['action' => 'index']);
    }
    $this->Flash->error('Unable to Delete user');
    return $this->redirect(['action' => 'index']);
}

Route File is here config/route.php

  <?php

   use CakeHttpMiddlewareCsrfProtectionMiddleware;
   use CakeRoutingRouteDashedRoute;
   use CakeRoutingRouteBuilder;


  $routes->setRouteClass(DashedRoute::class);

  $routes->scope('/', function (RouteBuilder $builder) {

   $builder->connect('/', ['controller' => 'Pages', 'action' => 
'display', 'home']);
  
  $builder->connect('/users/delete/{slug}', ['controller' => 'Users', 
'action' => 'delete']);

  $builder->connect('/pages/*', 'Pages::display');

  $builder->fallback();

});

Advertisement

Answer

I am sure it’s the CSRF token. Try to replace

<?= json_encode($this->request->getParam('_csrfToken')); ?>

with

<?= json_encode($this->request->getAttribute('csrfToken')); ?>

Also I am not sure about your “beforeSend: function(xhr)”, you can see a working ajax call example here:

https://stackoverflow.com/a/67253585/15256337

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement