How can i pass JavaScript variables back to PHP Controller in Drupal 8
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

&lt;?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' =&gt; '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){
        console.log(result.message);
}}