Show rendered node in jQuery modal through JSON Whenever a link has a specific class I want to show it as a jQuery modal. I have added the neccesarry data attributes to the link in order to be able to use it as a modal.

I have also created a route for nodes that has a custom controller that is run when a node is viewed with ?_format=json. The controller returns the rendered node as JSON which seems to work fine.

To see the route definition look here.

Here's my controller:

public function json(EntityInterface $node, $view_mode = 'full', $langcode = NULL) {
  $build = $this-&gt;entityTypeManager-&gt;getViewBuilder('node')-&gt;view($node, $view_mode);
  $output = $this-&gt;renderer-&gt;renderRoot($build);

  return new JsonResponse($output);
}


And here's the JS that makes the link a modal:

if ($(context).find('.class').length &gt; 0) {
  $(context).find('.class').each(function () {
    $(this).attr('data-dialog-type', 'modal').addClass('use-ajax');
  });
}


The only problem is that when clicking the link it gives an error saying:


  SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data


Why does JSON.parse fail to parse the JSON data that JsonResponse generates?
I can suggest you to check with AjaxResponse, it will return the json response object.

$response = new AjaxResponse();


And use below to open content in modal or as dialog.

$response-&gt;addCommand(new OpenModalDialogCommand($title, $content, ['width' =&gt; '700'])); // To open a modal window


OR

$response-&gt;addCommand(new OpenDialogCommand('#some-element', $title, $content, ['width' =&gt; '700'])); // to open a dialog window


$title refers to title of your node and $content refers to content that you want to show in the modal. It is also possible to define some properties like width in it.

And in the end just return it's response like below:

return $response;


Remember to include AjaxResponse in it your controller file.

use Drupal\Core\Ajax\AjaxResponse;


I hope the above will solve your problem.