I am working on one custom module and i need child categories when any ID is clicked. Loading is handle by ajax. I am not aware of ajax in Magento 2. Can anybody give me small demo of ajax in Magento 2..


1st Method:- You can use it instead of Ajax to Get Sub Category List Of Particular Parent Category In Magento:-

<select id="category" class="myinput-text required-entry widthinput" name="category">
  $parentid=5; // parent id which you want sub category
  foreach($categories as $cat){ 
   <option value="<?php echo $category->getId();?>"><?php echo $category->getName();?></option>
<?php } ?>


/* Load category by id*/
$cat = Mage::getModel('catalog/category')->load($id);

/*Returns comma separated ids*/
$subcats = $cat->getChildren();

//Print out categories string

foreach(explode(',',$subcats) as $subCatid)
  $_category = Mage::getModel('catalog/category')->load($subCatid);
    $caturl     = $_category->getURL();
    $catname     = $_category->getName();
      $catimg     = $_category->getImageUrl();
    echo '<h2><a href="'.$caturl.'" title="View the products for this category"><img src="'.$catimg.'" alt="" />'.$catname.'</a></h2>';

2nd Method:- You need to add a dependency to your class \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory.

Like this

protected $categoryCollectionFactory;
public function __construct(
    \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
) {
    $this->categoryCollectionFactory = $categoryCollectionFactory;
public function getDescendants($category, $levels = 2)
    if ((int)$levels < 1) {
        $levels = 1;
    $collection = $this->categoryCollectionFactory->create()
          ->addLevelFilter($category->getLevel() + $levels);
    return $collection;

now you just need to call the method getDescendants with the $category object as parameter and the number of levels you need for subcategories (2 in your case).

  • Thank u Vishal for u r answer .But I was looking for Magento 2 – Arzed Jan 19 '17 at 2:15

here is sample code make ajax call with jquery

require(['jquery', 'jquery/ui'], function($){ 
  $( "#search" ).click(function() {

    var searchval=$(this).val();
      method: "POST",
      url: "<?php  echo $block->getUrl('test/test/test'); ?>",
      data: { q: searchval },
      dataType: "json"
  .done(function( msg ) {

     // do here  




Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.