Drupal8:Basic Jquery Ajax custom module controller

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 :

Now we have to define the “global-scripting” in the MY-THME.libraries.yml

In js/ajax.js we add the usual Jquery ajax code

Let explain what we have define in the js/ajax.js:
1. The HTML Link to click:

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:

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:

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.

 

So now we have to extend the editContact($id) Method within the custom module Controller “ContactController”:

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.