3

I am using rsform pro to show dropdown option values from joomla database. I have 2 dropdown boxes, A list all the category name and its id while B lists all the available k2 items.

I have a jquery onchange function for A where it does an ajax request using joomla com_ajax, attached below are the codes. How can i use com_ajax to populate the B dropdown values based on the selection made on A ?

Plugin code

class plgAjaxK2progitems extends JPlugin
{
function onAjaxK2progitems()
{

    //$k2parid = (int) $_POST['id']; <- Old Method
    $input = JFactory::getApplication()->input;
    $k2parid = $input->post->get('id');

    // Prepare the database connection
    $db = JFactory::getDbo();
    $query = $db->getQuery(true);

    // Run the SQL query and store it in $results
    $query
        ->select($db->quoteName(array('u.id', 'u.title', 'u.catid', 'um.name')))
        ->from($db->quoteName('#__k2_items', 'u'))
        ->join('LEFT', $db->quoteName('#__k2_categories', 'um') . ' ON (' . $db->quoteName('u.catid') . ' = ' . $db->quoteName('um.id') . ')')
        ->where($db->quoteName('um.parent') ." = ".$db->quote($k2parid))
        ->where($db->quoteName('u.published') ." = ".$db->quote('1'))
        ->order($db->quoteName('u.id') . ' DESC');

    $db->setQuery($query);
    $results = $db->loadObjectList();

    return $results;

}

}

Ajax call

$(function() {
        $("#dept").change(function() {
        var $department = $(this).val();


        $.ajax({
            type: "POST",
            data: {id: $department},
            url: 'index.php?option=com_ajax&plugin=k2progitems&format=json',
            success: function(results) {

                console.log(results);                        

            }
        });
        });
    });

Console Log

Object { success: true, message: null, messages: null, data: Array[1] }

New Console log

Array[1]
0: Array[3]
 0: Object
    catid: "18"
    id: "9"
    name: "xxx"
    title: "yyy"
    __proto__: Object
 1: Object
    catid: "18"
    id: "10"
    name: "xxx"
    title: "yyy"
    __proto__: Object
 2: Object
    catid: "18"
    id: "11"
    name: "xxx"
    title: "yyy"
   __proto__: Object

Update Ajax Call - Working

$(function() {
        $("#dept").change(function() {
        var $department = $(this).val();


        $.ajax({
            type: "POST",
            data: {id: $department},
            url: 'index.php?option=com_ajax&plugin=k2progitems&format=json',
            success: function(results) {

                //console.log(results.data) <- removed this as no longer needed

               var $el = $("#progitems");
               var selectId = '#progitems';
                $el.empty(); // remove old options
                $el.append($("<option></option>")
                        .attr("value", '').text('Please Select Item'));

                // Iterate through results - worked with results.data[0]
                $.each(results.data[0], function(key, value) {
                    if ($(selectId+' option[value="'+value.id+'"]').length == 0) {
                        $(selectId).append($('<option/>').val(value.id).text(value.title+' - '+value.name));


                    }
                });


            }
        });
        });
    });
7
  • Please don't use $_POST with Joomla. Be sure to use JInput ;)
    – Lodder
    Commented Sep 22, 2015 at 23:09
  • Also, instead of console.log(results), could you try console.log(results.data.html)
    – Lodder
    Commented Sep 22, 2015 at 23:15
  • i've change the $_POST to use Jinput. when i use console.log(results.data.html) i get Undefined
    – Ron Modz
    Commented Sep 22, 2015 at 23:20
  • Oops, sorry, I meant console.log(results.data)
    – Lodder
    Commented Sep 22, 2015 at 23:23
  • now i see the objects but after i add $db->setQuery($query); somehow missed that :)
    – Ron Modz
    Commented Sep 22, 2015 at 23:41

2 Answers 2

2

You will need something like this:

var selectId = '#dropdownB'; // ID of your dropdown B 
var selected = ''; // Pass selected element here

// Iterate through results
$.each(results.data, function(key, value) {
    if ($(selectId+' option[value="'+value.id+'"]').length == 0) {
        $(selectId).append($('<option/>').val(value.id).text(value.title+' - '+value.name));

        // Add selected property
        if (key == selected) {
            $(selectId+' option[value="'+value.id+'"]').prop('selected', 'selected');
        }
    }
});

// Update Chosen if Joomla's Bootstrap is used
$(selectId).trigger("liszt:updated");
2
  • i am getting value "" and text as undefined-undefined . I've added my updated ajax call in the OQ
    – Ron Modz
    Commented Sep 23, 2015 at 10:45
  • Try $.each(results.data[0], function(key, value) { Commented Sep 23, 2015 at 13:20
0

use list type form field then trigger this script, edit according to your needs.

jQuery(document).ready(function(){
    var list = jQuery('#jform_list_ID');
    var parent = list.parent();

    list.trigger('chosen:updated');
    list.ajaxChosen({
        type: 'GET',
        url: ajax_url,
        dataType: 'json'
    }, function(response) {
        var results = [];
        var data = response.data || [];
        //change accordingly to the structure you provided
         var items = data[0] || [];

        if (items) {
            jQuery.each(items, function(i, item){
                results.push({
                    value: item.value,
                    text: item.text
                });
            });
        }
        return results;
    });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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