Ajax jquery Error cakephp 3.6.10 (Solved)

Hello. Im making a simple select change. But I have a problem ang getting the following error:

Error: [Cake\Http\Exception\InvalidCsrfTokenException] CSRF token mismatch.

This is my function on the controller:

public function municipios() {

    $this->viewBuilder()->layout('ajax');
   $this->LoadModel('Municipios');
    $subregion = $this->request->getData['subregion_id'];
    

        $municipios = $this->Municipios->find('list',[
            'limit' => 200,

            'conditions' => ['Municipios.subregion_id' => $subregion],
            'contain' => ['Subregiones']

           ]);

        $this->set(compact('municipios'));
        $this->set('_serialize', 'municipios');

    }

This is my jquery ajax:

$(document).ready(function () {
    $("#subregion-id").bind("change",
    function (event) {
      $.ajax({
    async:true,
    data: $("#subregion-id").serialize(),
    dataType:"html",
    success:
    function (data, textStatus) {
      $("#municipio-id").html(data);
      },
      type:"post", url:"\/lavaderos\/municipios"});
  return false;
      });
  });

I read on the documentation that need a token but I dont know how to do it.

That code work fine in 3.5.x but no in 3.6.x

Thank you

This may help
https://book.cakephp.org/3.0/en/controllers/components/csrf.html#csrf-protection-and-ajax-requests

Thanks rdd. Not woking :frowning:

are you using CSRF in your application ? if so you need to read the CSRF component with javascript in order to submit the post ajax request from jQuery !

No, only I need filter a select like countries states. Work fine in cakephp 3.5.

you must get an error. what does your logs look like? see in the error logs. You may find the answer there !

Error log:

2018-08-08 10:04:28 Error: [Cake\Http\Exception\InvalidCsrfTokenException] CSRF token mismatch.
Request URL: /lavaderos/municipios
Referer URL: http://localhost:8765/lavaderos/add

I dont Know what is “CSRF token mismatch”, first time that happen.

The function and the jquery script previosly mentioned work fine in cakephp 3.5.x but not working on 3.6.10

Like I said before, you have to read the CSRF to send in your post request from $.ajax() so your controller reads it and treats your request as a legit request from the web-app. I am not sure if cakePhP 3.6 has the CSRF component loaded by default. Check the resources on the website about the CSRF component.

https://book.cakephp.org/3.0/en/controllers/components/csrf.html

Ultimately, try to disable the component on your controller just for testing purposes, I DO NOT RECOMMEND to disable it on production.

public function beforeFilter(Event $event)
{
    $this->getEventManager()->off($this->Csrf);
}

I found the solution. Just add new line in jquery script:

$(document).ready(function () {
    $("#subregion-id").bind("change",
    function (event) {
      $.ajax({
    async:true,
    data: $("#subregion-id").serialize(),
    dataType:"html",
    beforeSend: function (xhr) { // Add this line
        xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val());
    },  // Add this line
    success:function (data, textStatus) {
      $("#municipio-id").html(data);
    },
      type:"post", url:"\/lavaderos\/municipios"});
  return false;
      });
  });
2 Likes