David
David

Reputation: 453

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 !

Upvotes: 0

Views: 7962

Answers (2)

Luca Reghellin
Luca Reghellin

Reputation: 8101

A couple of examples on how to build an ajax link (you can then use it on an ajax call):

example 1: link to a regular controller (assume an OrderDetailCustom controller):

{$link->getPageLink('order-detail-custom', true)}

//you will then use it like this (note ajax:true):
$.get(ajax_link, {'id_order': id_order, 'ajax': true});

//the controller will then generally have some 
//utility functions based on Tools::getValue('ajax') or
//$this->isXmlHttpRequest(); > a builtin Controller class's function

example 2: link to a module's controller (assume a SimpleMailer example modile and a SendSimpleMail module controller)

{$link->getModuleLink('simplemailer','sendsimplemail',[],true)}

Please take a look to these functions in the Link class code. Also, for this last example, see here how to build a module controller and how the naming works:

how to generate a link to a module controller in prestashop?

Upvotes: 0

Altaf Hussain
Altaf Hussain

Reputation: 5202

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

Upvotes: 2

Related Questions