I have a custom module which uses a Javascript library called Bootstrap Table. Among other things, this library allows me to create tables with clickable rows. Currently, I can pass variables from the PHP Controller into the Javascript library. These variables are used to feed the fields in the table.

What I want to do next, is to define an event (when a row is clicked) which would then return the value of the row and pass it back to the PHP controller.

The controller would use this returned variable to perform some specific action and update the information displayed in the table.

As far as I know, I should use AJAX, but so far I have not been able to accomplish what I want.

This is some of the info I have found.


How do I pass JavaScript variables back to PHP?

controller function use with ajax

1 Answer 1


You're right, you'll need to create a php controller for this task.

This involves a number of steps

In your custom module you'll need to add your controller in /yourmodules/src/Plugin/rest/resource

In this example I created one called HelloRest.php


namespace Drupal\my_module\Plugin\rest\resource;

use Drupal\Driver\Exception\Exception;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
 * Provides a resource for accepting rest calls
 * @RestResource(
 *   id = "hello_rest",
 *   label = @Translation("Hello Rest Handler"),
 *   uri_paths = {
 *     "canonical" = "/hello/{name}",
 *     "https://www.drupal.org/link-relations/create" = "/hello"
 *   }
 * )

class HelloRest extends ResourceBase {
     * Responds to GET requests.
     * Returns a watchdog log entry for the specified ID.
     * @param int $id
     *   The ID of the watchdog log entry.
     * @return \Drupal\rest\ResourceResponse
     *   The response.

    public function get($name = '') {
        $response = ['message' => 'Hello '.$name];
        return new ResourceResponse($response);

Then I enabled the route using the REST UI module here https://www.drupal.org/project/restui to do so. There is probably another way to enable the route but I'm not sure how. Also you want to make sure every role you need has permissions to access the rest call. In my case I wanted everyone that visited the site to have access so I had to make sure that anonymous users had access to that route.

Now that you have that created all you have to do is perform an ajax call to it to get your response back.

jQuery.ajax({url: location.protocol + "//" + location.host + "/hello/"+name+ '?_format=json", success: function(result){

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.