Call a prestashop module with ajax

user7722025 picture user7722025 · Mar 21, 2017 · Viewed 10.1k times · Source

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>

Answer

Matt Loye picture Matt Loye · Mar 21, 2017

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');

}
}