Jump to content

Prestashop 1.6 controller ajax call


AyyoubEL
 Share

Recommended Posts

i'am looking for the right way to call an action from my controller (modules/mymodule/front/mymodule.php) using Ajax (js).

For example i had this function (TestMyAjax), how call i call it trought ajax.

 

public function TestMyAjax()
{
echo 'OK';
}

Edited by AyyoubEL (see edit history)

Share this post


Link to post
Share on other sites

You have to create a FrontController, defaut.php

class ModuleNameDefaultModuleFrontController extends ModuleFrontController
{
    public function initContent(){
        $row = array();
        parent::initContent();
        if(Tools::getValue('ajax')){
            $id_product = (int)Tools::getValue("id_product");
            if($id_product){
                $row['id_product'] = $id_product;
                $product_informations = Product::getProductProperties($this->context->language->id, $row);
            }
           if (isset($product_informations) and $product_informations)
               $json = array(
                   'productInformations' => $product_informations
               );
            else
                $json = array(
                    'status' => 'error',
                    'message' => $this->l('Error when getting product informations.')
                );

         } else

             $json = array(
                 'status' => 'error',
                 'message' => $this->l('Error when getting product informations.')
             );
         die(Tools::jsonEncode($json));
    } 
}

 

 

JS in the TPL

var id_product = $('input[name="id_product"]').val();
$.ajax({
    type: "POST",
    url: '{$link->$this->context->getModuleLink('modulename', 'default')}',
    async: false,
    cache: false,
    data: "product_id="+id_product+"&ajax=1",
    success: function(html){
        $("#price").html(html.price);
        $('#link').html(result.productInformations.link);
    },
    error: function() {
        alert("ERROR:");
    }
});

You can see using ajax in admin also in this article http://magento-web.blogspot.com/2017/01/utilisation-dajax-en-front-et-back.html

it's in frensh, but i think that the code is clear.

Best regards.

Edited by tarek.fellah (see edit history)
  • Like 2

Share this post


Link to post
Share on other sites

  • 3 years later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

Cookies ensure the smooth running of our services. Using these, you accept the use of cookies. Learn More