I am trying to just invoke callback in my AJAX response.
Currently I have the following response.
private function responseWithSuccess($message, $status_code = 200)
{
$ajax_response = new AjaxResponse();
$ajax_response->setStatusCode($status_code);
$response =
[
'status' => 'success',
'message' => $message
];
$ajax_response->setContent(\GuzzleHttp\json_encode($response));
return $ajax_response;
}
It returns a response of the specified format, but is it possible to listen for the response text in this case ?
I've found that I have to use the Drupal Command class that is used for communication.
So I created the custom Command, here is code
class CustomCallbackCommand implements CommandInterface, CommandWithAttachedAssetsInterface
{
use CommandWithAttachedAssetsTrait;
/**
* The content for the dialog.
*/
protected $message;
/**
* Constructs a \Drupal\mymodule\Ajax\BootstrapModalCommand object.
*/
public function __construct($message)
{
$this->message = $message;
}
/**
* {@inheritdoc}
*/
public function render()
{
return array(
'command' => 'onCustomCallback',
'message' => $this->message,
);
}
}
And add it to response like that
private function responseWithSuccess($message, $status_code = 200)
{
$ajax_response = new AjaxResponse();
$ajax_response->setStatusCode($status_code);
$response =
[
'status' => 'success',
'message' => $message
];
$ajax_response->addCommand(new CustomCallbackCommand($response));
//$ajax_response->setContent(\GuzzleHttp\json_encode($response));
return $ajax_response;
}
But when I try to send the request, an error appears.
Fatal error: Call to a member function getLibraries() on null in /public_html/core/lib/Drupal/Core/Ajax/AjaxResponse.php on line 48
What is wrong with my code ?
So basically the main question is how to call specific callback when a response comes back.
P.S.
I know that I could just override default handlers of the Drupal JS module, but I am looking for a better way.