Thomas Gensou
Thomas Gensou

Reputation: 76

Ajax request to override controller in prestashop 1.6

outside the conventional methods of ajax requests from a prestashop module, I would like to use a ajax method from product.js and retrieve data from an override controller.

my function in product.js :

function attrReference(ref){
    $.ajax({
        url: baseUri,
        async: true,
        cache: false,
        type:'GET',
        dataType : "json",
        headers: { "cache-control": "no-cache" },
        data: {
                controller :'product',
                action :'attrReference',
                token : token,
                ajax: 1,
                ref : ref
        },
        success: function(data){

        }
    });
}

My override controller product :

class ProductController extends ProductControllerCore{

public function displayAjaxAttrReference(){
   echo '<pre style="background:yellow">';
   print_r($_GET);
   echo '</pre>';
   exit;
}

}

From the documentation, i use displayAjax to recover data, unless this is not the right method, I tried many attempts but none are correct.

Do you have any idea?

Upvotes: 2

Views: 3294

Answers (1)

kawashita86
kawashita86

Reputation: 1573

If you need to retrieve data, or little piece of html i suggest to avoid the displayAjax function since it's called only at the end of the controller routine, and thus you will get everything processed (retrieving of template, database query and so on). normally the controller function are called with the following list:

init();
setMedia();
// postProcess handles ajaxProcess
postProcess();
initHeader();
initContent();
initFooter(); 
displayAjax() || display();

as you can see displayAjax should be avoided if you don't want to retrieve the whole page/a template the require all the information of the product page. To correctly route your request you should override also the postProcess function of your product controller such that:

public function postProcess(){
   if(Tools::isSubmit('action') && Tools::getValue('action') == 'attrReference') 
        $this->AjaxGetReference();
  parent::postProcess();
}

and then

public function AjaxGetReference(){
   echo '<pre style="background:yellow">';
   print_r($_GET);
   echo '</pre>';
   die();
}

Also, always remember to pass the id_product with your ajax function if you are interacting with the ProductController, else any action will fail becouse of the init function:

public function init()
{
    parent::init();

    if ($id_product = (int)Tools::getValue('id_product'))
        $this->product = new Product($id_product, true, $this->context->language->id, $this->context->shop->id);

    if (!Validate::isLoadedObject($this->product))
    {
        header('HTTP/1.1 404 Not Found');
        header('Status: 404 Not Found');
        $this->errors[] = Tools::displayError('Product not found');
    }
}

Upvotes: 4

Related Questions