How to attach variables to drupalSettings with ajax? With the page attachments function, I can easily attach a library or some variables to drupalSettings.
Now however, I want to replace some HTML code with ajax AND attach some variables to drupalSettings. While the ajax call does work in replacing HTML, it does not work in attaching or passing along the variables to drupal Settings.
Is there a way I can do both? Here is my code.
public static function AddAJAXResponseCommands(AjaxResponse $response = NULL, array $params = []) {

  $modalSettings = [
    'id' =&gt; 1,
    'status' =&gt; true,
  ];

  $sample = [
    '#type' =&gt; &quot;html_tag&quot;,
    '#tag' =&gt; &quot;div&quot;,
    '#attributes' =&gt; ['class' =&gt; ['context-menu']],
    '#value' =&gt; &quot;Dashboard&quot;,
  ];

  $sample['#attached']['library'][] = 'mylibrary/dashboard-js';
  $sample['#attached']['drupalSettings']['dashboard']['myVariables'] = $modalSettings;

  $response-&gt;addCommand(new ReplaceCommand('.context-menu', $sample));
  return $response;
}

When I attempt to access drupalSettings.dashboard.myVariables which I confirmed already works when I use the page attachment function, it does not work when using ajax calls. Instead I get myVariables is undefined.
I console logged drupalSettings and sure enough, my variables are no where to be found in there. How can I get it added? Is page attachment the only way to do this?
Use the SettingsCommand
$settings=['ajax_forms_test' =&gt; ['foo' =&gt; 42]]; /* An array of key/value pairs of JavaScript settings. */
$merge=TRUE; /* (Optional) Booleen Whether the settings should be merged into the global drupalSettings. */
$response-&gt;addCommand(new SettingsCommand($settings,$merge));

So your code would become something like this:
public static function AddAJAXResponseCommands(AjaxResponse $response = NULL, array $params = []) {

  $modalSettings = [
    'id' =&gt; 1,
    'status' =&gt; true,
  ];

  $sample = [
    '#type' =&gt; &quot;html_tag&quot;,
    '#tag' =&gt; &quot;div&quot;,
    '#attributes' =&gt; ['class' =&gt; ['context-menu']],
    '#value' =&gt; &quot;Dashboard&quot;,
  ];

  $sample['#attached']['library'][] = 'mylibrary/dashboard-js';
  $merge = TRUE;
  $settings['dashboard']['myVariables'] = $modalSettings;
  $response = new AjaxResponse();
  $response
    -&gt;addCommand(new ReplaceCommand('.context-menu', $sample))
    -&gt;addCommand(new SettingsCommand($settings, $merge));
  return $response;
}