Drupal 8 Module - How to use AJAX?

I'm currently trying to use AJAX (with jQuery) in my Drupal 8 module to reload a page when a user types something into a text box. I managed to get the full HTML page, but I would like the AJAX function to receive only the contents of the page (without the whole layout).

How can i achieve this? What should I change in my controller function to display a different view when the request uses AJAX?

I searched on Google and on Drupal 8 documentation, but I did not find the answer to my question.

Thanks in advance for your help!

+4
source share
2 answers

AJAX, .

$build[] = array(
    '#type' => 'markup',
    '#markup' => '<p>Demo text content</p>',
);
return new Response(render($build));

Response

use \Symfony\Component\HttpFoundation\Response;
+3

, ajaxAction, :

$.ajax({
  type:  'GET',
  url:   'ajaxContent.php?action=get&pageId=777',
  cache: false
}).done(function( receivedHtml ) {
  $("#targetBlock").html(receivedHtml);
});

jQuery ajax ajaxContent URL.

-2

Source: https://habr.com/ru/post/1666130/


All Articles