Drupal 8 load view data using Ajax call


Here I am explaining a simple use case where we have to display a content type data in a node body based on a dropdown options.

So here whenever user selects drop down it will make Ajax call to load data from a view.
Here we achieving this in below steps.

Here we are taking a simple use case where we are adding content of contact details for each city.
Following configurations we are going to create at back end

1. Create Contacts content type
2. Create a view block with context filter
3. Custom module code to load view
4. Select box in any other content type node
5. Jquery Ajax call to load data

1. Create Contacts content type
Here we are creating a content type called contacts.
Below fields are added in this content type.
• Opening hours
• Contact person
• Contact city
• In body field you can add address details
Here contact city is the list box with city values in the list all other fields are text fields.

Add content to this content for each city. Select each city and add contents related to that city.
2. Create a view

Create a block view and select display format as table.

Add required fields in to view block

 

Here we are changing block machine name in to a more readable name contacts_block

Also add City as a context filter

3. Custom module code to load view

Now we are going to add code to load this block . So we need to do below things in our custom module.
Here my custom module name is digital_nadeem.
So first I am going to add entry to add controller and URL details in digital_nadeem .routing.yml file.
Below URL we are going to call from Jquery Ajax .
URL -https://www.yourdomain.com /custom/ajax/contacts
SO for that we are creating corresponding details as shown below

Now we are going to create controller which will load view block.
Here we are creating a controller called contacts controller in below Path.
Your_project_dir\modules\custom\digital_nadeem\src\Controller\contactsController.php
Create a function contactDetails to load view.

4. Select box in any other content type node
Now we have to add dropdown in node content of any other content type. Create a page with content and add drop down with city name and values as city name.

5. Jquery Ajax call to load data

Above jquery function is self explanatory as it loads data when user selects city. So data will be loaded in table format so that you can apply styles according to your needs.

you can download this module by clicking here




Get Free E-book
Get a free Ebook on Drupal 8 -theme tutorial
I agree to have my personal information transfered to MailChimp ( more information )

You may also like...