Generate drupalSettings in Ajax Callback I'm returning a form with #ajax functionality in an Ajax response. The form is properly loaded into the page, however it is not #ajaxified, as the drupalSettings are not being returned. In D7, we could generate the JS settings AKA Drupal.settings using the following code:

$scripts = drupal_add_js();
if (!empty($scripts['settings']))
{
    $settings = '&lt;script type="text/javascript"&gt;jQuery.extend(Drupal.settings, ';
    $settings .= drupal_json_encode(call_user_func_array('array_merge_recursive', $scripts['settings']['data']));
    $settings .= ');&lt;/script&gt;';
}


I'm trying to find the D8 equivalent of this code, but not having much success. At the moment I'm returning a JsonResponse from my ajax callback, but I'm thinking I probably need to return an AjaxResponse. What I can't figure out is how to pass my generated form to the AjaxResponse, in order for it to return the settings along with the HTML for the form.
Well, I'm answering my own question. The secret is to use BubbleableMetadata. Here is my code explaining what I did and how it happened. Here is my entire controller response that generates the JSON for the response:

 public function ajax_callback($type)
 {
    // Retrieve the form
    $form = \Drupal::service('form_builder')-&gt;getForm('Drupal\path\to\Form');

    // Render the form
    $rendered_form = render($form);

    // Get the data from BubbleMetaData
    $data = BubbleableMetadata::createFromRenderArray($form);
    // Retrieve the attachments from the $data
    $attachments = $data-&gt;getAttachments();

    // Generate the settings to be sent back with the ajax response
    if(!empty($attachments['drupalSettings']))
    {
        $settings .= '&lt;script type="text/javascript"&gt;jQuery.extend(drupalSettings, ';
        $settings .= Json::encode($attachments['drupalSettings']);
        $settings .= ');&lt;/script&gt;';
    }

    // Send back the rendered form along with the settings
    $response = [
        'content' =&gt; $rendered_form . $settings,
        'status' =&gt; TRUE,
        'type' =&gt; $type,
    ];

    // Return the data as a JsonResponse
    return new JsonResponse($response);
}