8 – How to load a webform via ajax inside custom JS?

Try the following steps :

  1. Create follow this how to create contact form block
  2. Create route for example form/contact-us-block :

custom_module.routing.yml

custom_module.get_contact_form_block:
  path: '/form/contact-us-block'
  defaults:
    _controller: 'Drupalcustom_moduleControllerTutorialController::getContactFormBlock'

getContactFormBlock Action in your controller

public function getContactFormBlock() {
    //- Set your block id here
    $bid = 4;
    $block = Drupalblock_contentEntityBlockContent::load($bid);
    $build = Drupal::entityTypeManager()
      ->getViewBuilder('block_content')
      ->view($block);
    return render($build)->__toString();
  }
  1. Get the block html in your Js.

    (function ($, Drupal) {
      $(document).ready(function ($) {
        $.ajax({
          url: 'form/contact-us-block',
          success: function (response) {
            console.log(response);
          },
          error: function (error) {
            console.log(error);
          }
        });
      });
    })(jQuery, Drupal);