• Hello Fabrik Community

    Fabrik is now in the hands of the development team that brought you Fabrik for Joomla 4. We have recently transitioned the Fabrik site over to a new server and are busy trying to clean it up. We have upgraded the site to Joomla 4 and are running the latest version of Fabrik 4. We have also upgraded the Xenforo forum software to the latest version. Many of the widgets you might have been used to on the forum are no longer operational, many abandoned by the developers. We hope to bring back some of the important ones as we have time.

    Exciting times to be sure.

    The Fabrik 4.0 Official release is now available. In addition, the Fabrik codebase is now available in a public repository. See the notices about these in the announcements section

    We wish to shout out a very big Thank You to all of you who have made donations. They have really helped. But we can always use more...wink..wink..

    Also a big Thank You to those of you who have been assisting others in the forum. This takes a very big burden off of us as we work on bugs, the website and the future of Fabrik.

change dropdown element in the form depend on the date user select

tanya2015

Member
hello! How to change dropdown values depend on the value that user choose in the other field (date in my case) in the form?
Use dropdown eval? Or something else?
 
Hello Hugh, thank you for your fast and useful support. I mean actual options available in dropdown. They must changed depend on date and room. I need user to choose date after this he must to choose room, and depending on date and room dropdown available are changed.
Actually as I understand I need dynamic dependent dropdown that's mean to use ajax but I don't understand how and where to implement it. I think so - user choose date, after this he choose room if changed room(conference hall) dropdown show times when it's free (this I need for time start and for the end time)
 
Last edited:
yes i think i need user ajax, but i need to update 2 dropdown fields start(time) and end (time) when room (conference-hall is choosing), and i don't know much about ajax.
 
actually this code I need to get dropdawn for start time and the same but with $end for end time. but how can i do the same for the end(time)

for start time i use
function getInfo(){
var hall = $('vks___hall').getValue(); //the watched element
var update = $('vks___start'); //field to update

var data = {
'option' : 'com_fabrik',
'format' : 'raw',
'task' : 'plugin.userAjax',
'method' : 'getData',
'hall' : hall
};
new Request({
'url': '',
'data': data,
onComplete:function(r){
update.value = r;
}
}).send();
}


class userAjax {
function getData(){

/*Time array hall works from 8 a.m. to 19 p.m.*/
$starttime = 8;
$endtime = 19;
$stepmin = 30;
$lower = $starttime * 3600;
$upper = $endtime * 3600;
$step = $stepmin * 60;
$times = [];
foreach (range($lower, $upper, $step) as $increment)
{
$increment = gmdate('H:i', $increment);
list($hour, $minutes) = explode(':', $increment);
$date = new DateTime($hour.':'.$minutes);
$times[] = (string) $increment;
}
/*looking for the conference date and transform it's format */
$vksdate = $formModel->formData['vks___datavks'];
$vksdate1 = new DateTime($vksdate);
$vksdate_fin = $vksdate1->format('Y-m-d');

/*get hall value */
$hall = JRequest::getVar('hall', '');
/*$hall = $formModel->formData['vks___hall'];*/
/*$formModel->setFormErrorMsg("hall: [" . $hall . "]!!!!!!");*/

/*Search times for date and hall user choose in the database */
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('COUNT(*)');
$query->from($db->quoteName('vks'));
$query->where($db->quoteName('datavks')." = ".$db->quote($vksdate_fin).' AND '.$db->quoteName('hall')." = ".$db->quote($hall));
$db->setQuery($query);
$count = $db->loadResult();
/*$formModel->setFormErrorMsg("count: [" . $count . "]!!!!!!");*/
/*if where is no date in database*/
if ($count == 0)
{echo $times;}
/* if date exist, got times reserved from database, find difference with all possible times/
else {
$query = $db->getQuery(true);
$query->select($db->quoteName('start'))->from($db->quoteName('vks'))->where($db->quoteName('datavks')." = ".$db->quote($vksdate_fin).' AND '.$db->quoteName('hall')." = ".$db->quote($hall));
$db->setQuery($query);
$column= $db->loadColumn();
$times_start = Array();
foreach ($column as $key => $val)
{ $times_start[$key] = substr($val, 0, -3);
}
$times1 = array_diff($times, $times_start);
echo $times1;}
}
}
 
Here is what I used (also, please use the code insertion tool rather than just pasting the code so the formatting is retained), you will need to change function and var names to fit your system:
onChange javascript:
JavaScript:
function eventOnClick(el) {
    var repeatID = el.element.get('value');
    jQuery.ajax({
        url: "index.php?option=com_fabrik&format=raw&task=plugin.userAjax&method=getEventAttendees&rp_id=" + repeatID,
        type: "POST",
        dataType: "json",
        beforeSend: function (){
            jQuery("#loader").show();
        },
        complete: function(data) {
            jQuery("#loader").hide();
        },
        success: function(data, status) {
            jQuery('#___attendee').empty();    // Clear the existing options
            jQuery('#___attendee').append('<option value="0">Please select</option>' + data);
        },
        error: function(data, status) {
            alert("Data: " + data + "\nStatus: " + status);
        }
    });
}

the userAjax function:
PHP:
        public function getEventAttendees()
        {
            require_once(JPATH_SITE.'/custom_scripts/jevents/helper.php');
            $app = JFactory::getApplication();
            $input = $app->input;
            $rp_id = $input->get('rp_id', '');
            if (empty($rp_id)) {
                echo json_encode("no repeat ID");
                exit;
            }
            $attendees = get_primary_attendees(["repeatID"=>$rp_id]);
            $options = [];
            /* Convert to an array of names keyed by attendee ID */
            foreach ($attendees as $attendee) {
                $options[$attendee->id] = JFactory::getUser($attendee->user_id)->name;
            }
            /* Sort by name */
            asort($options);
            /* Now convert to an option string */
            $optionString = "";
            foreach ($options as $id => $name) {
                $optionString .= '<option value="'.$id.'">'.$name.'</option>';
            }
            echo json_encode($optionString);
        }
You won't have my helper file or my getPrimaryAttendees function but you should be able to get the idea of what is going on for your use case.
 
Code:
hello
achartier, thank you for help.
I use code, in javascript
----------------------------
var $datavksID = $('vks___datavks_cal');
var datavks = $datavksID.value;
var result;
if (datavks === '')
    {
      alert ('Select date');
     }
else
  {
   alert (datavks);
   var $hallID = $('vks___hall');
   var hallvks = $hallID.value;
   jQuery.ajax({
            url: "index.php?option=com_fabrik&format=raw&task=plugin.userAjax&method=getStartTime",
            type: "POST",
            async: false,
            data: {"hall": hallvks, "datavks": datavks },
            dataType: "json",
            error: function () {
                alert( "Error :(" );},
    });
alert (hallks);
}
---------------------------and php at the beginning
public function getStartTimes()
        {$app = JFactory::getApplication();
            $input = $app->input;
            $hall = $input->get('hall', '');
            $datavks = $input->get('datavks', '');
             echo json_encode($hall,$datavks);
             exit;
}
------------------------------------------------------------

but nothing work I got  only error message
 
Last edited:
As achartier said ... "(also, please use the code insertion tool rather than just pasting the code so the formatting is retained)" ... by which he means the code insert button in the editor (the one to the left of the disk icon).

It makes code a hundred times easier to read.

-- hugh
 
A number of things. You do not need an exit in your php function, just let the function close.

In your ajax call you do not have a success function which should do something with the response.

In your error function add the data & status params and output them in an alert as I have done.

One thing that helps in debugging ajax stuff is to open the developer console in your browser and watch the network traffic. Often the response to the ajax call can be seen there and will give you a better idea of what the problem is.
 
Thank you.
Php is already in user_ajax.php
I correct code
Code:
var $datavksID = $('vks___datavks_cal');
var datavks = $datavksID.value;
if (datavks === '')
  {alert ('Select date');}
else
{
  var $hallID = $('vks___hall');
  var hall = $hallID.value;
      jQuery.ajax({
            url: "index.php?option=com_fabrik&for=plugin.userAjax&method=getStartTimes",
            type: "POST",
            data: { hall: hallvks,  datavks: datavks },
            dataType: "json",
            error: function(data, status) {
            alert("Data: " + data + "\nStatus: " + status);},
        success: function(data, status) {
            jQuery('vks___time1').empty();
            jQuery('vks___time1').append('<option value="0">Please select</option>' + data);},
            });
 
  }
and I got
Data: [object Object]
Status: error, and 500 internal server error in debug. Year ago it was paid support and this year I tryed to find it - no success. Such nasty ajax I met first time.
I think that something wrong with data.... but in alert everything is ok with hall and vks
 
Data will be an object as you have rightly json encoded it in the user_ajax function. But, your alert is attempting to make a string out of it using the + sign so all it shows is the [object Object]. If you alert it separately you should see the contents of the object. Or use the developer console and see what the network response is to your ajax call.

Also, your user_ajax function is simply returning data and you are appending it to the dropdown. You need to convert this data into select options. This needs to happen in your user_ajax function (as I do) or in your javascript success function. Look at the code sample I provided.
 
I use for element event on click

my code javascript
Code:
var $datavksID = $('vks___datavks_cal');
var datavks = $datavksID.value;
if (datavks === '')
  {alert ('Select date');}
else
{
  var $hallID = $('vks___hall');
  var hallvks = $hallID.value;
      jQuery.ajax({
            url: "index.php?option=com_fabrik&format=raw&task=plugin.userAjax&method=getStartTimes",
            type: "POST",
            data: {'hall':hallvks, 'datavks':datavks},
            dataType: "json",
            error: function(data, status) {
                alert(data);},
            success: function(data, status) {
                 jQuery('vks___time1').append('<option value="0">Please select</option> + data');},
            });
    }

user_ajax.php

Code:
public function getStartTimes()
{ $starttime = 8;
  $endtime = 19;
  $stepmin = 30;
  $lower = $starttime * 3600;
  $upper = $endtime * 3600;
  $step = $stepmin * 60;
  $times = [];
  foreach (range($lower, $upper, $step) as $increment)
    {
        $increment = gmdate('H:i', $increment);
        list($hour, $minutes) = explode(':', $increment);
        $date = new DateTime($hour.':'.$minutes);
        $times[] = (string) $increment;
    }
    $optionString = "";
            /* Convert to an array of times */
    foreach ( $times as $key => $value ) {
    $key = $key+1;
    $id = (string) $key;
    $optionString .= '<option value="'.$id.'">'.$value.'</option>';
}
         echo json_encode($optionString);    
}
I don't use values from ajax, just want array of times 8.00, 8.30 … 19.00 were as options.
------------------------
debug
------------------------
See request-string_and_form-data.png and response.png
As I got error something wrong in my php. But when I try to echo something, nothing going on. and status 500 internal server error. no data as I understand.
 

Attachments

  • event-click.png
    event-click.png
    8.7 KB · Views: 111
  • request-string_and_form-data.png
    request-string_and_form-data.png
    5 KB · Views: 102
  • responce.png
    responce.png
    26 KB · Views: 108
Is that response really what the network tab in dev tools is showing, ie. that's literally what the server is returning?

If so, then your user_ajax.php is wrong ... is it literally what you pasted, just the function, with no php tags or class? If so, it needs to look like this:

Code:
<?php
/**
 * User ajax example
 *
 * @package     Joomla
 * @subpackage  Fabrik
 * @copyright   Copyright (C) 2005-2015 fabrikar.com - All rights reserved.
 * @license     GNU/GPL http://www.gnu.org/copyleft/gpl.html
 */

// No direct access
defined('_JEXEC') or die('Restricted access');

/**
 * Define your userAjax class
 *
 * @package     Joomla
 * @subpackage  Fabrik
 * @since       3.0
 */
class UserAjax
{
    /**
    * This is the method that is run. You should echo out the result you which to return to the browser
    *
    * @return  void
    */
    public function getStartTimes()
    {
        $starttime = 8;
        $endtime   = 19;
        $stepmin   = 30;
        $lower     = $starttime * 3600;
        $upper     = $endtime * 3600;
        $step      = $stepmin * 60;
        $times     = [];

        foreach (range($lower, $upper, $step) as $increment)
        {
            $increment = gmdate('H:i', $increment);
            list($hour, $minutes) = explode(':', $increment);
            $date    = new DateTime($hour . ':' . $minutes);
            $times[] = (string) $increment;
        }

        $optionString = "";

        /* Convert to an array of times */
        foreach ($times as $key => $value)
        {
            $key          = $key + 1;
            $id           = (string) $key;
            $optionString .= '<option value="' . $id . '">' . $value . '</option>';
        }
       
        echo json_encode($optionString);
    }
}

I've removed the large chunk of comments, but left the important bits.

-- hugh
 
Thank you very much Hugh and achartier it works fine, I make big mistake because at the beginning I did so, but later delete these necessary part and didn't notice it and thank you for the help with debug, now I know how to use this system.
 
And one more question I have very strange behavior of data. data: {'hall':hallvks, 'datavks':datavks, 'ind':ind},
everything is OK with data beside hallvks (hall). $hall = $input->get('hall', ''); - use this code in user_ajax.php.
I check my code in PHP (PHP form plugin and get good results) Using the same code in user-ajax, I got wrong result. I check everything and discover what hallvks has wrong value in user_ajax, although in data it's correct. In form (ua1.png). In consol (debug) - form data - ua2.png - rad marked data - correct. And I insert
echo json_encode($hall). Result I've got for $hall marked red. it's just "1" (mean $hall=1;, but it must be upload_2019-7-28_2-36-39.png in data upload_2019-7-28_2-32-12.png. I think that problem in language...Because all other data has language independent, Don't know howto solve this problem....
Thank you for the help.
P.S. It's a problem with encoding may be I try $hall = iconv("UTF-8", "WINDOWS-1251", $hall); but got the same result....
try to use header("Content-type: text/html; charset=windows-1251") in php, no results.
 

Attachments

  • ua1.png
    ua1.png
    4.5 KB · Views: 106
  • ua2.png
    ua2.png
    4.7 KB · Views: 101
  • ua3.png
    ua3.png
    7.9 KB · Views: 115
Last edited:
Ajax call is sending ua2.png
index.php
but when I use echo $hall in user_ajax.php and see console I see that $hall=1.
 
If that's the value you are sending from the Javascript when you make the AJAX call, ie. the value of the vks___datavks_cal element ... is that element a dropdown? If so, that will be the value, not the label.

-- hugh
 
We are in need of some funding.
More details.

Thank you.

Members online

Back
Top