Ajax call for dependent comboboxes in joomla plugin 3.0

I am trying to get a ajax call working in a joomla plugin. In the plugin, there are two comboboxes: project level 1 and project level 2. Project level 2 is dependent on the project level 1 and gets loaded from a MySQL table according to the selection of project level 1 (table bda_level_2). The table bda_level_2 contains a field level1_id which is a foreign key to the table bda_level_1 (project level 1). Project level 1 is also populated from a MySQL table (table bda_level_1).

The ajax call is a POST request which contains the project level 1 id in the data field: a parameter with name l1_id. Somehow, the ajax call to populate the second combobox seems to fail. I don’t know if it has to do with the format of the request or with the retrieval of the parameter from the request, since there is no way to get logging of the problem.
Here is the code of the templ/default.php file:

<?php defined('_JEXEC') or die;

?>
<form>

        Project level 1:
        <select name="level1" class="level1">
        <option selected="selected">--Select Level 1--</option>
        <?php

        // Get a db connection.
        $db = JFactory::getDbo();

        // Create a new query object.
        $query = $db->getQuery(true);

        // Select records
        $query->select($db->quoteName(array('id', 'level1')));
        $query->from($db->quoteName('bda_level_1'));
        $query->order('level1 ASC');


        // Reset the query using our newly populated query object. 


        $db->setQuery($query);

        if($rows = $db->loadAssocList()){

          foreach($rows as $row){

            $level1_id=$row['id'];
            $data=$row['level1'];

            echo '<option value="'.$level1_id.'">'.$data.'</option>';
          }
        }

        ?>
        </select> 


        <br/><br/>

        Level 2:

        <select name="level2" class="level2">

        <option selected="selected">--Select Level 2--</option>

        </select>


</form>

file helper.php

<?php defined('_JEXEC') or die;

class modProjectLevelAjaxHelper
{
    public static function getAjax()
    {
        $result = ""; 

        $input = JFactory::getApplication()->input;
        $id  = $input->post->get('data');

        $db = JFactory::getDbo();
        // Create a new query object.

        $query = $db->getQuery(true);
        $conditions = array(
            $db->quoteName('level1_id') . ' = ' . $db->quote($id));

        // Select records
        $query->select($db->quoteName(array('id', 'level2')));
        $query->from($db->quoteName('bda_level_2'));
        $query->where($conditions);
        $query->order('level2 ASC');

        // Reset the query using our newly populated query object. 
        $db->setQuery($query);

        if($rows = $db->loadAssocList()){

        foreach($rows as $row){

          $level2_id=$row['id'];
          $data=$row['level2'];

          $result += '<option value="'.$level2_id.'">'.$data.'</option>';

          }
        }
        return $result;
    }
}

file mod_project_level_ajax.php

<?php defined('_JEXEC') or die;

// Include the helper.
require_once __DIR__ . '/helper.php';

// Instantiate global document object
$doc = JFactory::getDocument();

$js = <<<JS
(function ($) {
    $('.level1').change(function () {
                var value   = $('.level1').val();
                var dataString = 'l1_id='+value;
                var request = {
                    'option' : 'com_ajax',
                    'module' : 'project_level_ajax',
                    'data'   : dataString,
                   'format' : 'raw'
                };                                
        $.ajax({
            type   : 'POST',
            data   : request,
            success: function (response) {
                $('.level2').html(response);
            }
        });
        return false;
     });
})(jQuery)
JS;

$doc->addScriptDeclaration($js);

require JModuleHelper::getLayoutPath('mod_project_level_ajax');

file mod_project_level_ajax.xml

<?xml version="1.0" encoding="utf-8"?>
<extension type="module"
           version="3.0"
           method="upgrade">
    <name>Project Level Ajax</name>
    <creationDate>January 17, 2014</creationDate>
    <author>Matt Thomas</author>
    <authorUrl>http://betweenbrain.com</authorUrl>
    <copyright>Copyright (C) 2013 betweenbrain llc. All rights reserved.      </copyright>
    <license>GNU General Public License version 2, or later.</license>
    <version>3.0.1</version>
    <description>Project Level Ajax!</description>

    <files>
        <filename module="mod_project_level_ajax">mod_project_level_ajax.php</filename>
        <filename>helper.php</filename>
        <folder>tmpl</folder>
    </files>

</extension>

create script of the tables:

DROP TABLE IF EXISTS `bda_level_1`;
CREATE TABLE `bda_level_1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `level1` varchar(200) COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

DROP TABLE IF EXISTS `bda_level_2`;
CREATE TABLE `bda_level_2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `level1_id` int(11),
  `level2` varchar(200) COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`),
  CONSTRAINT FOREIGN KEY (`level1_id`) REFERENCES `bda_level1`(`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO bda_level_1 (`id`,`level1`) VALUES
(1,'Security'),
(2,'Cyber Security');

INSERT INTO bda_level_2 (`id`,`level2`,`level1_id`) VALUES
(1, 'Access Control Systems',1),
(2, 'Biometrics',1),
(3, 'CCTV & Associated Systems',1),
(4, 'Tracking Systems',1),
(5, 'Sensing Systems and Heads',1),
(6, 'Fire',1),
(7, 'Intruder Alarm Systems',1),
(8, 'Information & Data Security',1),
(9, 'Manned Security Services',1),
(10, 'Security Hardware',1),
(11, 'Weapons & Ammunition',1),
(12, 'Communications',1),
(13, 'Personnel Protection & Control',1),
(14, 'Vehicles',1),
(15, 'Audio Equipment & Systems',1),
(16, 'Ancillary Security Equipment & Services nec',1),
(17, 'Bomb Disposal',1),
(18, 'Forensics & Evidence',1),
(19, 'CBRN & Anti Terrorism',1),
(20, 'Cyber Threat Intelligence',2),
(21, 'System Recovery & Data Cleansing',2),
(22, 'Situational Awareness Products',2);

Any help is greatly appreciated.


Source: ajax

Leave a Reply