PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 27, 2022

[FIXED] How to invoke a backend function in JS in a Smarty template used in a Prestashop module?

 October 27, 2022     prestashop, prestashop-1.7, smarty     No comments   

Issue

In a custom prestashop module, I am trying to dynamically show children categories in a dropdown.

This is the code I add in the hook before calling the template:

$subcatObj = new Category("24");
$subcatObj2 = $subcatObj->getSubCategories($this->context->language->id);

$this->context->smarty->assign('seriesCategories', $subcatObj2 );

This is how I use this in the template:

<select id="series_dropdown" class="selectpicker" data-style="btn-primary">
    {foreach from=$seriesCategories item=seriesCategory}
        <option value="{$seriesCategory.id_category}">{$seriesCategory.name}</option>
    {/foreach}
</select>

What I need is to invoke this getSubCategories with different values from JS, to dynamically populate the dropdown. So instead a hardcoded 24, I would like to use a JS variable.

$subcatObj = new Category(******** JAVASCRIPT VARIABLE *********);
$subcatObj2 = $subcatObj->getSubCategories($this->context->language->id);

What shall be done to achive this? -It is sort kind of AJAX web service-

Prestashop 1.7.1


Solution

You need create a php file in your module to handle the ajax request, eg:

/modules/your_module/ajax.php

<?php

require_once(dirname(__FILE__).'/../../config/config.inc.php');

$subcatObj = new Category((int)Tools::getValue('id_category'));
$subcatObj2 = $subcatObj->getSubCategories((int)Context::getContext()->language->id);

die(Tools::jsonEncode($subcatObj2));

Now in JavaScript inside the .tpl, or by a .js file loaded there:

$.ajax({
    url: '/modules/your_module/ajax.php',
    type: 'POST',
    dataType: 'JSON',
    data: { id_category: $('#series_dropdown').val() }
})
.done(function(data) {
    console.log(data); // 'data' should contain the response of corresponding sub-categories
})
.fail(function() {
    console.log('An error has occurred!');
});

PD. This is a basic example, you should add some security token in the ajax.



Answered By - Rolige
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing