Search code examples
phpjqueryjoomla

How to avoid processing HTML outside of the template for Joomla components?


I create my own component in Joomla 3.x I have a functionnal Ajax call like this :

file.js

jQuery.ajax({
  type: 'post',
  data: 'topo_id=' + idTopo,
  url: 'index.php?option=com_mycomp&task=getMyData&format=json', 
  datatype: "json",
  success: function(res) {
    console.log(res);
    jQuery('#resultDiv').html(res.data);
},
error: function (e) {
  console.log(e);
}})

controller.php

function getMyData(){
  $mydataSQL = $MyClass->getMyData($param); // 
  $mydataHtml = $this->formatHtml($mydataSQL);  // to replace div content with ajax 
  echo new JResponseJson($mydataHtml); 
}
function formatHtml(MyClassFoo $foo) {
  $html ='<div id="foo">' . $foo->bar . '</div>';
  $html .= '<h1>' . $foo->foo .'</h1>';
  ...... and more html code here
  return $html
}

I'd like to use the result ($myData = result PDO::FETCH_CLASS) in a view. ($mydataSQL->name, $mydataSQL->address...) to avoid processing the html in the controller function.

I tryed without success a call like this : ...&format=raw&view=newview.


Solution

  • What you want here is to use a layout.

    https://docs.joomla.org/J3.x:Sharing_layouts_across_views_or_extensions_with_JLayout

    in your controller

    private function formatHtml(MyClassFoo $foo) 
    {
       $layout      = new JLayoutFile('path.to.layout');
       $data = array('foo' => $foo);
    
       return $layout->render($data);
    }
    

    and in layouts/path/to/layout.php (or templates/#current template#/html/layouts/path/to/layout.php)

    <?php
    defined('JPATH_BASE') or die;
    
    $foo = $displayData['foo'];
    ?>
    <div id="foo"><?= $foo->bar ?></div>
      <h1><?= $foo->foo ?></h1>
      <p>and more...</p>
    </div>