Call a prestashop module with ajax
11,682
Solution 1
In a new file at the module root, you can create a file "ajax.php"
require_once(MODULE_DIR.'MyMenu/mymenu.php');
if(Tools::getValue('token') !=
$mymenu = Module::getInstanceByName('mymenu');
$menu = $mymenu->hookFooter();
die($menu);
In your js, at the root of your module
<script>
$(document).ready(function (e) {
$.ajax({
method: "POST",
url: "./ajax.php",
data: {},
success: function (data) {
$('.load_menu').html(data);
}
})
});
</script>
Solution 2
The best way is to do it via a front controller linked to your module. You can call the url like this :
$link->getModuleLink('modulename','controller', $parameters);
// Parameters is an optionnal array, it can be empty
And for the controller, place a file like this ./modules/modulename/controllers/front/ajax.php with this kind of content :
class ModuleNameAjaxModuleFrontController extends ModuleFrontController
{
public function initContent()
{
$response = array('status' => false);
require_once _PS_MODULE_DIR_.'modulename/modulename.php';
$module = new ModuleName;
if (Tools::isSubmit('action')) {
$context = Context::getContext();
$cart = $context->cart;
switch (Tools::getValue('action')) {
case 'actionname':
$response = array('status' => true);
break;
default:
break;
}
}
// Classic json response
$json = Tools::jsonEncode($response);
$this->ajaxDie($json);
// For displaying like any other use this method to assign and display your template placed in modules/modulename/views/template/front/...
// $this->context->smarty->assign(array('var1'=>'value1'));
// $this->setTemplate('template.tpl');
// For sending a template in ajax use this method
// $this->context->smarty->fetch('template.tpl');
}
}
Author by
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
I have a PrestaShop module called 'MyMenu' and I want call this menu with an AJAX call. My module is displayed in the
hookFooter()
method:public function hookFooter() { $display = $this->display(__FILE__, 'megamenu.tpl', $smartyCacheId); Tools::restoreCacheSettings(); return $display; }
I want display with this script:
<div class="load_menu"></div> <script> $(document).ready(function (e) { $.ajax({ method: "POST", url: "../modules/MyMenu.php", data: {}, success: function (data) { $('.load_menu').html(data); } }) }); </script>