In the previous tutorial (drupal8-create-module-with-multiple-route-and-custom-route-contoller-twig-template/) we have create a custom modul using different Route and some TWIG templates. Now we want to call one of the route using Ajax .
First of all, we should have create a custom theme and add our custom JavaScript file in MY-THME.info.yml :
1 2 |
libraries: - office/global-scripting |
Now we have to define the “global-scripting” in the MY-THME.libraries.yml
1 2 3 4 5 |
global-scripting: js: js/ajax.js: {} dependencies: - core/jquery |
In js/ajax.js we add the usual Jquery ajax code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
jQuery(document).ready(function($){ $('#main').on( "click", '.callController',function(event) { event.preventDefault(); var href = $(this).attr('href'); var html = $.ajax({ type: "POST", url: href, data: {"ajaxCall":true}, async: false }).responseText; if(html != "error"){ window.history.pushState("object or string", "Title", href); $("#content").html(html); return false; } else { $("#content").html('error'); return false; } return false; }); }); |
Let explain what we have define in the js/ajax.js:
1. The HTML Link to click:
1 2 3 4 5 |
<div id="main">.... <a class="callController" href="/contact/edit/12">Edit</a> ... </div> <div id="content"></div> |
2. Then we have to prevent to reload the page with: event.preventDefault();
3. We get the content of the href attribute, because this will be the Ajax Route call:
1 |
var href = $(this).attr('href'); |
4. Now we start the Ajax call , we will add a post variable, that indicate our controller that we are comming from an ajax request.
5. We set the URL in the browser with the Route using:
1 |
window.history.pushState("object or string", "Title", href); |
Why we do this ? Simple , if Google will index our link or user disable Javascript in the browser , we have then to be sure that the link will works without the ajax call . In the Controller we will have a condition using the post variable “ajaxCall”.
6. The Controller response will then displayed in the content div.
1 |
$("#content").html(html); |
So now we have to extend the editContact($id) Method within the custom module Controller “ContactController”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public function editContact($id) { $tplVariables = [ '#theme' => 'contact_edit_page', '#id' => $id ]; //Refreshing the page or comming from Search Engine.This will render the whole HTML page. if (!isset($_REQUEST['ajaxCall'])) return $tplVariables; //The Ajax call. This will render only the TWIG template. return new Response(render($tplVariables)); } |
You will be able now to call your own Business Logic, extend and transfer your variables to the TWIG tempalte.
IMPORTANT: Don’t forget to define your variables first in mymodule.module . Clearing the cache if no changes can be very helpful.