4

I want that js script running after doing the ajax action.

For example, its work for Drupal 7:

  Drupal.behaviors.events = {
  attach: function(context, settings) {
    $('#example').bind('ajaxSuccess', function(data, status, xhr) {
      >>code here<<
    });
  }
};

how to write a successful script for Drupal 8?

Jerzy Stuhr
  • 63
  • 2
  • 7

1 Answers1

1

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.

Kevin Wenger
  • 1,484
  • 1
  • 13
  • 29
  • but I do not need to write a php code. I do not need to create a form. I want to just have the JS handler on the run after a successful ajax hang. And Drupal 7 my example worked. I think Drupal 8 has changed a little bit. – Jerzy Stuhr Jun 08 '18 at 09:44
  • So it seems your question is misleading. You should add some more information. Example, *which form* or *action* are you trying to "hook" after an Ajax call this is related to a core module or a contrib module ? – Kevin Wenger Jun 08 '18 at 14:35
  • well, the module is from the core. Form for editing the user profile. Add a picture of the user. And I want, that when the picture is loaded (or deleted), this is just an Ajax form. My js code should work. – Jerzy Stuhr Jun 08 '18 at 18:59