jQuery.ajax() results in a 403 error I created a custom block and I was trying to use the ajax method of jQuery, but it seems that whenever I access the method of the controller, it returns a 403 error.

This is my contoller (custom_blocks/src/Controller/CustomBlocksController.php)

namespace Drupal\custom_blocks\Controller;
use Drupal\Core\Controller\ControllerBase;

class CustomBlocksController extends ControllerBase
{
  // $variable is the wildcard from the route
  public function ajaxCallback($variable)
  { 
    return ucwords($variable);
  }
}


This is my routing file (custom_blocks/custom_blocks.routing.yml).

my.route:
  path: '/sample-page/{variable}'
  _defaults:
    _controller: 'Drupal\custom_blocks\Controller\CustomBlocksController::ajaxCallback'
    _permission: 'access content'
    _access: 'TRUE'


This is my custom JavaScript code (custom_blocks/js/command.js).

(function($, Drupal) {
     $('#custom-button').click(function(){
        var name = 'john doe';
        $.ajax({
             type : "POST",
             url: '/sample-page/' + name,
             success : function(response){
                  console.log(response);
             },   
        }, 'html');
     });
})(jQuery, Drupal);


Hope someone can help me.
That's because by default Drupal only allows GET request on default controllers. In your case you should create a custom resource.

Using resources has multiple advantages:


No custom paths per request method
Access control
CSRF protection
Using the API that the REST module in Drupal 8 provides


It basically comes down to creating a class with an annotation:

             /**
              * @RestResource(
              *   id = "my_resource",
              *   label = @Translation("Resource label"),
              *   uri_paths = {
              *     "canonical" = "/sample-page"
              *   }
              * )
              */
             class CustomResource extends ResourceBase {
                public function post($data) {
                  // Do stuff with the posted data.
                }
             }


Some more elaborate examples:

Example one

Example two

You will have to alter your jQuery POST request to something like:

 $.ajax({
         type : "POST",
         url: '/sample-page/',
         data: {'uid':2},
         success : function(response){
              console.log(response);
         },   
    });


The data you post in your jQuery request will be available in $data of your resource class.