CakePHP 3.5 AJAX and CSRF

Hello,

I want to update the database using URLs and not a form.

Here is my URL

<a href="#"  data-action="prive" title="private profil"  id="setupprofil"  onclick="return false;"><span class="glyphicon glyphicon-remove-circle"></span>&nbsp;private profil</a>

Data processing is done using the following script

$(document).on('click','#setupprofil',function() {

  var action = $(this).data("action"); // private or public

  console.log($('[name="_csrfToken"]').val()); // Returns correctly the generated CSRF token

  $.ajax({
            url: '/instatux/settings/setup_profil',
            dataType: "text json",
            type: "POST",
            data: {action: action},
            beforeSend: function(xhr) {
        xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val());
    },

When I click on this url to update the database I get the following error message

‘_Token’ was not found in request data.

Is it possible to transmit the CSRF token to the controller by not coming from a form ?

Thank you in advance

_Token is not the CSRF token, it’s something used by the security component to prevent form tampering.

Hello @christ57,
When we create a CakePHP form and then based on the input fields the CakePHP generates a hidden field named _TOKEN.
Here is the StackOverflow solution in detail,
https://stackoverflow.com/a/51990800