Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 8 module - How to use AJAX?

I'm currently trying to use AJAX (with jQuery) in my Drupal 8 module in order to reload a page when the user types something in a textfield. I managed to get a full HTML page back but I would like the AJAX function to only get the content of the page (without the whole layout).

How can I achieve that? What shall I change in my controller function in order to render a different view when the request uses AJAX?

I have searched on Google and on the Drupal 8 documentation but I have not found any answer to my question.

Thanks in advance for your help!

like image 396
Dominique Avatar asked Oct 18 '22 19:10

Dominique


1 Answers

You can return the data in AJAX callback function as below.

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

Make sure to include the Response class

use \Symfony\Component\HttpFoundation\Response;
like image 88
Jose D Jo Avatar answered Oct 30 '22 21:10

Jose D Jo