By using an object \Drupal\Core\Ajax\InvokeCommand
on a \Drupal\Core\Ajax\AjaxResponse::addCommand()
.
Ajax can be used with forms to provide various things. The typical steps involved:
- Create a form.
- Within a
::buildForm()
use a #ajax
render element.
- Create the callback.
There are two ways to respond to the ajax request. You may either respond with an AjaxResponse
object or with HTML to replace the element with which may either be raw HTML or a render array.
To invoke your own Javascript function - as you want - you have to respond with an AjaxResponse
object.
Here is a complete documentation of Ajax on Drupal 8.
Here is the example:
Partial ::buildForm()
with the implementation of Ajax render element:
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Send'),
'#ajax' => [
'callback' => [$this, 'respondToAjax'],
]
];
Here is the Ajax callback method, in the same form:
/**
* @param array $form
* Form API array structure.
* @param array $form_state
* Form state information.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* Response object.
*/
public function respondToAjax(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$response->addCommand(new InvokeCommand('#example', 'ajaxSuccess'));
return $response;
}
You can find here a list of all commands you can pass in the response.