Fetch tpl file in ajax response on admin controller in prestashop. When we need to code same thing on multiple page or multiple controller in prestashop then we usually think to save our time and code effort. Even we think to make a global file, which can be used on multiple controllers.
How to fetch tpl file in ajax response
Here, we will tell you, “how to fetch tpl file in ajax response” while working on admin controller in prestashop.
Step :1 First create a .tpl file in your hook directory (views/templates/hook). Directory can be changed accordingly, we are taking example.
Here, we have putted a file in – views/templates/hook/abc.tpl. Now i want to use abc.tpl on both controller (Front/Admin).
Step :2 Html Code –
<button id="yourID" class="btn btn-primary" type="button">Add More</button>
Ajax Code –
$(document).on('click', '#yourID', function() { $.ajax({ url : path, cache : false, type : 'POST', data : { ajax: true, action: "fetchTPL", }, success : function(result) { if (result) { $('#addContent').last().append(result); } } }); });
As we know, whenever we pass ajax and action parameter while sending request using ajax on controller to manipulate the data, it process on same controller with a prefix added function eg – ajaxProcessFetchTPL().
Step :3 Admin Controller Code –
public function ajaxProcessFetchTPL() { $data = array(); // array is empty, you can work accordingly here //after processing all data just assign it to smarty of content $this->context->smarty->assign(array( 'youContentData' => $data) ); // to fetch a tpl file use fetch method and use die function to return the response to ajax die($this->context->smarty->fetch(_PS_MODULE_DIR_.'modulename/views/templates/hook/abc.tpl')); }
Checkout above code, when ajax request will call the function ajaxProcessFetchTPL(), You can processe all the manipulation with variables and data according to your requirement, after that we have assigned all data in a smarty context which we will use on tpl file.
Now you can simply call fetch function of smarty to retrieve the .tpl file from the directory. die() function will return the response to ajax data/result, where have append whole tpl file into a html element.
If there are something not understandable by this post then do comment below. We will surely assist on that.