Dedicated Magento 2 Blog

How to Render an HTML Using an Ajax Call in Magento 2 Module

In the previous article, we have displayed the form success action message using ajax. In that article, we have returned only the specific message from our controller and display it on the frontend. Sometimes you need to return the whole HTML and display it on frontend using Ajax. Today we will see How to render an HTML using an Ajax call in Magento 2 Module.

Magento 2 provides a Magento\Framework\Controller\Result\JsonFactory class that can be use to return an JSON response from a controller. We will use factory method of this class to return our HTML in json format.

Create PHTML File

Create a PHTML file index.phtml under app/code/Codextblog/Custom/view/frontend/templates from where we want to initialize our ajax call.

In this file, we have created one blank div with id #ajaxresponse. Using ajax call we will call controller file and return an HTML. Using JQUERY we will fill that HTML into div.

Under the script tag, we are passing two parameters to our js file. First is AjaxUrl which is the URL of the controller (in our case it is custom/index/view/, a custom is the front name of our module and view.php is our controller file) from where we will return a JSON response, second is CurrentProduct which is product id. You can pass any other parameters in this call. For demonstration purpose, we have passed product id to CurrentProduct parameter.

You can see, in the line no. 54 and 55 we have passed block file and template file in which we will write our business logic and HTML code respectively. We have passed the currentproductid in setData method so that it is available in block file for any business logic. In line number 59 we are setting our data in setData method which is preparing JSON output.

Want to ask a question or leave a comment?

Leave a Comment

How does full page cache affect ajax queries like this? Will the response be cached if I want to return customer specific data, e.g. show info specific to the customer on product page which should not be cached and shown to other customers!