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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.