How do I set up a Drupal 8 Module to be an AJAX service?
October 9, 2017
File structures seem a lot different in Drupal 8, and I’m still getting the hang of them. This is an example of a simple module I made, so hopefully it can be a good starting point for you too!
my_module/my_module.info.yml
name: Module Name Here
type: module
description: Description of the module
core: 8.x
my_module/my_module.module
<?php
//basically any code you want your module to do
//ex: any functions that need API calls or data that you call in any preprocessor functions
use Drupal\my_module\Controller\DefaultController as MyModule;
function my_module_get_data(){
$data = MyModule::hello_world();
return json_decode($data->getContent());
}
**Drupal 8 includes a way to make URLs via a routing.yml file.
my_module/my_module.routing.yml
#GENERAL
my_module.hello_world:
path: '/my_module/hello_world'
defaults:
_controller: '\Drupal\my_module\Controller\DefaultController::hello_world'
requirements:
_permission: 'access content'
my_module/src/Controller/DefaultController.php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends ControllerBase{
public static function hello_world(){
return new JsonResponse(true);
}
}
So in this example: now if you go to http://mywebsite.com/my_module/hello_world if will call the defaultcontroller in your module and print out JSON you can use in an ajax call. You’ll also notice I can use it on the server side as well (my_module.module)
To me this was a lot easier or a process than Drupal 7 was. Happy Drupal Coding!