Aliassse Aliassse - 7 months ago 188
Javascript Question

Call controller function through an AJAX call in prestashop 1.5

I'm trying to call controller function through an AJAX call in Prestashop 1.5. I don't even know if it's possible. This is what I did :
I override product controller (in override/controllers/front/ProductController.php) to load extra medias and to do some actions that the default controller does not do. This is what my controller looks like :

<?php

class ProductController extends ProductControllerCore
{

public function setMedia() {

parent::setMedia();

// Add extra ressources
// CSS
$this->addCSS(...)
$this->addJS(array(...));

}

// Extra methods
public function renderCart() {
echo '<h2>HELLO</h2>';
}


}


Here is my question: How can I call my renderCart() function through an AJAX call ? Is that even possible ?

Thanks for your help !

Answer

You can call directly the renderCart() function, instead you can do it the other way. Normally every controller has a few predefined functions which are

 init() 

and initContent()

Every one has its own details and purpose, so I am not going to explain them here.

Now what you have to do it to create another function in your controller called init() and then call your renderCart function with it. Check the sample code below

public function init() 
 {
    parent::init();  //First you have to call the parent init to initialize resources
    if($this->ajax) //special variable to check if the call is ajax
    {
      $this->renderCart(); // call your function here or what ever you wanna do
    }
 }

I hope from code comments you will understand.

Note: This is a sample code and is not tested. It is just for giving you the idea

Thank you