I need to to create dependent dropdown. First select the client. In the next dropdown list it will shows the listof projects that belongs to the selected client. After selecting the project third dropdown list will filter tasks belongs to that project. I need to do this with a one table in the database without primary key foreign key relationship.
My task table have
1.client name
2. project name
3. tasks name
here one client has multiple project
one project has multiple tasks
Maybe I'm asking very simple question.But I am unable to proceed with my project without doing this part.Please someone helps me.
This is my table structure
If you are using same table to store Client, Projects & Tasks, So it's possible you will create more duplicate records e.g. Might be project name duplicate or task duplicate or client name ....
Although it's up to your choice and convenient.. Basically Ajax Dropdown (Dependent dropdown) is fully action & Ajax based. So you know what and when you want through Ajax then you can build this easy..
Here is an example for CodeIgniter Lovers!! :D
CodeIgniter Controller:
<?php
// security first always....
(defined('BASEPATH') or exit('No direct script access allowed'));
/**
* Class Controller
*
* Class Dropdown Controller to handle login & logout
*/
class Dropdown extends CI_controller
{
/**
* Class Constructor
*/
public function __construct()
{
// execute parent class constructor
parent::__construct();
// load model
$this->load->model('Dropdown_model');
}
/**
* Default method to execute if method name missing
* #return [type] [description]
*/
public function index()
{
$array_data = array();
// only on Ajax Request
if ($this->input->is_ajax_request()) {
// if request for projects
if ($this->input->post('action') && $this->input->post('action') == 'project') {
// get client name
$client = $this->input->post('client', true);
// get project data by client name
$array_data = $this->Dropdown_model->get_dropdown_data(trim($client), 'project');
// AjaxPOST JSON response
echo json_encode($array_data);die();
}
// if request for task
if ($this->input->post('action') && $this->input->post('action') == 'task') {
// get project name
$project = $this->input->post('project', true);
// get task data by project
$array_data = $this->Dropdown_model->get_dropdown_data(trim($project), 'task');
// AjaxPOST JSON response
echo json_encode($array_data);die();
}
}
// else get all client data
$array_data = $this->Dropdown_model->get_dropdown_data(null, null);
// send to view
$this->load->view('dropdown', ['data' => $array_data]);
}
}
/* End of file dropdown.php */
/* Location: ./application/controllers/dropdown.php */
CodeIgniter Model:
<?php
// No direct script execution
defined('BASEPATH') or exit('No direct script access allowed');
/**
* Class Dropdown_model to handle all related information from MySQL
*/
class Dropdown_model extends CI_Model
{
/**
* MySQL table which contains all data about users
* #var string
*/
protected $table = 'task';
/**
* Returns, User First Name by Email ID
* #param [type] $email_addres [description]
* #return [type] [description]
*/
public function get_dropdown_data($where_data = null, $type = null)
{
$query = '';
// clients only
if (is_null($type) && is_null($where_data)) {
// desire column from table
$this->db->select('client_name');
// only unique clients
$this->db->distinct('client_name');
// mysql table
$query = $this->db->get($this->table);
}
// projects by client
elseif ($type == 'project' && !is_null($where_data)) {
// desire column from table
$this->db->select('project_name');
// where clause
$this->db->where('client_name', $where_data);
// mysql table
$query = $this->db->get($this->table);
}
// task by project
elseif ($type == 'task' && !is_null($where_data)) {
// desire column from table
$this->db->select('task');
// where clause
$this->db->where('project_name', $where_data);
// mysql table
$query = $this->db->get($this->table);
}
// if record exist
if ($query->num_rows() > 0) {
// return all data as array
return $query->result_array();
} else {
// error
return false;
}
}
}
/* End of file Dropdown_model.php */
/* Location: ./application/models/Dropdown_model.php */
CodeIgniter View:
<!DOCTYPE html>
<html>
<head>
<title>CodeIgniter: Dependent dropdown list by using single table value</title>
<!-- load bootstrap css -->
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- load jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- load bootstrap js -->
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="form-group">
<label for="name">Client</label>
<select class="form-control" id="clients" name="clients">
<option value="0">--Select Clients--</option>
<?php if (isset($data)):?>
<?php foreach ($data as $key => $value): ?>
<option value="<?=$value['client_name']?>"><?=$value['client_name']?></option>
<?php endforeach ?>
<?php endif ?>
</select>
</div>
<div class="form-group">
<label for="name">Projects</label>
<select class="form-control" id="projects" name="projects">
<option value="0">--Select Projects--</option>
</select>
</div>
<div class="form-group">
<label for="name">Tasks</label>
<select class="form-control" id="tasks" name="tasks">
<option value="0">--Select Tasks--</option>
</select>
</div>
<div class="form-group">
<input type="button" class="btn btn-primary" value="Submit">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
// client select box
var $client = $('select#clients');
// project select box
var $projects = $('select#projects');
// task select box
var $tasks = $('select#tasks');
// on change client name, get projects
$client.on('change', function () {
// get selected client name
var client = $(this).find('option:selected').val();
// post data with CSRF token
var data = {
action:'project',
client: client,
"<?=$this->security->get_csrf_token_name()?>" : "<?=$this->security->get_csrf_hash()?>"
};
// AjaxPOST to get projects
$.post('./dropdown', data, function(json) {
projects_data = '<option value="0">--Select Projects--</option>';
$.each(json, function(index, obj){
projects_data += '<option value="'+obj.project_name+'">'+obj.project_name+'</option>';
});
// append all projects in project dropdown
$projects.html(projects_data);
}, 'JSON');
});
// on change project, get task
$projects.on('change', function () {
// get selected project name
var project = $(this).find('option:selected').val();
// AjaxPOSt wit CSRF
var data = {
action:'task',
project: project,
"<?=$this->security->get_csrf_token_name()?>" : "<?=$this->security->get_csrf_hash()?>"
};
$.post('./dropdown', data, function(json) {
task_data = '<option value="0">--Select Task--</option>';
$.each(json, function(index, obj){
task_data += '<option value="'+obj.task+'">'+obj.task+'</option>';
});
// append all task data in Task dropdown
$tasks.html(task_data);
}, 'JSON');
});
});
</script>
</body>
</html>
MySQL table:
id client_name project_name task
------ ------------------- ----------------- -------------
1 Man Powers & Morans Web Micro Site Development
2 Mango vs Trees Brand Development Pitch
3 Man Powers & Morans Ecom Site Maintenance
4 Light One Ecom Site Maintenance
5 Mango vs Trees Siteground Development
MySQL table structure:
Field Type Null Key Default Extra
------------ ----------- ------ ------ ------- ----------------
id int(11) NO PRI (NULL) auto_increment
client_name varchar(85) YES (NULL)
project_name varchar(85) YES (NULL)
task varchar(85) YES (NULL)
Html View Screenshot:
that i understand from your question.
You may need to make select fields like this
<label>Clints</label>
<select name="clint" id="clint" class="form-control" onchange="return get_projects(this.value)">
<option value="">Select Clint</option>
<?php foreach($clients as $clint){?>
<option value="<?php echo $clint->id?>"><?php echo $clint->name?></option>
<?php }?>
</select>
<label>Projects</label>
<select name="projects" id="projects" class="form-control" onchange="return get_tasks(this.value)">
<option value="">All</option>
</select>
<label>tasks</label>
<select name="tasks" id="tasks" class="form-control">
<option value="">All</option>
</select>
and Script like this
function get_projects(clint_id) {
$.ajax({
url: '<?php echo base_url();?>your controllef/your function/' + clint_id,
success: function(response)
jQuery('#projects).html(response);
}
});
}
function get_tasks(project_id) {
$.ajax({
url: '<?php echo base_url();?>your controllef/your function/' +project_id,
success: function(response)
{
jQuery('#tasks).html(response);
}
});
}
then you need to make function in controller like this
public function get_projects($clint_id)
{
$project = $this->your_model->get_projects($clint_id);
echo '<option value="">Select Project</option>';
foreach($project as $row){
echo '<option value="' . $row->project . '" >' . $row->name . '</option>';
}
}
public function get_tasks($project_id)
{
$tasks = $this->your_model->get_tasks($project_id);
echo '<option value="">Select Project</option>';
foreach($tasks as $row){
echo '<option value="' . $row->task . '" >' . $row->name . '</option>';
}
}
Related
Hi I successfully designed a chat message system between users and it works fine. The only problem I am having at this point is polling data from chat table to browser real time.
The messages are displayed using ajax and the setInterval works as I checked the console. The issue is that it does not capture new entries to the table for display and hence the user has to keep refreshing the page to see new content.
Please help. My code is below. Please forgive my file naming convention as I will change it later on.
PS this is developed using codeigniter framework.
**Chats.php - Controller**
public function ajax_get_chat_messages(){
echo $this->_get_chat_messages();
}
function _get_chat_messages($recipient = null)
{
$user_id = $this->session->userdata('user_id');
$recipient = $this->input->post('recipient');
$data['recipient'] = $this->User_model->get_users($user_id);
$data['chats_count'] = $this->Chats_model->get_chat_messages_count($recipient);
$content = $this->Chats_model->get_chat_messages_count($recipient);
$data['chats'] = $this->Chats_model->get_chat_messages($user_id);
$result = array('status' =>'ok', 'content'=>$content);
return json_encode($result);
}
**Model - Chats_model.php**
public function get_chat_messages_count($recipient = null){
$session = $this->session->userdata('user_id');
$this->db->select('*');
$this->db->from('chat_messages');
$this->db->join('users', 'users.user_id = chat_messages.user_id');
$this->db->where(array('chat_messages.user_id' => $session));
$this->db->where(array('chat_messages.recipient' => $recipient));
$this->db->or_where(array('chat_messages.user_id' => $recipient));
$this->db->where(array('chat_messages.recipient' => $session));
$this->db->where_in(array('chat_messages.chat_id' => $session , $recipient));
$query = $this->db->get();
return $query->result_array();
}
**View - chats_view.php**
<script type="text/javascript">
var user = "<div class='timeline-item' id='view'><ul><?php foreach($chats_count as $chat){echo '<li>'; echo $chat['username']; echo '</li>'; }?></ul></div>";
</script>
<div class="wrapper wrapper-content">
<div class="row animated fadeInRight">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>Chat</h5>
<div class="ibox-tools" >
</div>
</div>
<div class="ibox-content inspinia-timeline" id="view1" >
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
**JS - chat2.js**
$(document).ready(function(){
setInterval(function() { get_chat_messages(); }, 2500)
$("input#chat_message").keypress(function(e){
if(e.which == 13){
$("a#submit_message").click();
return false;
}
});
function get_chat_messages(){
$.post(base_url +"user/chats/ajax_get_chat_messages",{user: user}, function(data) {
if(data)
{
var current_content = $("#view1").html();
$("#view1").html(user);
console.log(user);
}
else
{
}, "json");
}
get_chat_messages();
});
Images attached showing the table structure, the chat page on browser and console data.
[Chat page on browser, only showing username for testing purposes][1]
[Chat Table][2]
[Console Data, only showing username for testing purposes][3]
This is my controller. here i declared current_company.
public function index($id='')
{
$this->load->model('Company_model');
($id!='') ? $data["company_details"]=$this->Company_model->get_company($id) :'';
($id!='') ? $data ["current_company"]=$this->Company_model->get_currentcomp($id) :'';
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage',($id!='') ? $data : '');
$this->load->view('includes/footer');
}
This is my model. Here i declared the function
class Company_model extends CI_Model{
protected $strTableName = 'suc_company';
function __construct(){
parent::__construct ();
$this->db->from($this->strTableName);
}
function get_currentcomp($intPkId){
$this->db->where('pk_bint_company_id',$intPkId);
$q1 = $this->db->get($this->strTableName);
return $q1->result_array()[0];
}
This is the view part. here i called the $current_company !== FALSE then
<div class="form-group">
<label for="company_package" class="col-sm-3 control-label"> Package</label>
<div class="col-sm-9 col-xs-12">
<?php if ($current_company !== FALSE ) {?>
<select name="company_package" class="form-control select2" disabled="">
<option value="<?php echo $company_package;?>" selected=""><?php echo $packagename;?></option>
</select>
<?php } else { ?>
<?php } ?>
Error
an error is occurring... undefined data current_company
Change your controller code like this.
public function index($id='')
{
$this->load->model('Company_model');
$data["company_details"] = false;
$data["current_company"] = false;
if($id != ''){
$data["company_details"] = $this->Company_model->get_company($id);
$data["current_company"] = $this->Company_model->get_currentcomp($id);
}
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage',$data);
$this->load->view('includes/footer');
}
As said in comment, you are leaving possibility that maybe $data wouldn't be passed to view file. You have to restrict this kind of oscillations.
Try this way:
public function index($id='')
{
if ((int)$id < 1) {
redirect('some/generic/place', 'refresh');
}
// we have integer in parameter
// so we will check if data by that parameter exists
$data = [];// initialization of array so we are sure $data is set
$this->load->model('Company_model');
$data['company_details'] = $this->Company_model->get_company($id);
if ($data['company_details']) {
$data['current_company'] = $this->Company_model->get_currentcomp($id) :'';
} else {
// in this point $data is an empty array
}
// $this way variable will be available in all view files
$this->load->var($data);
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage');
$this->load->view('includes/footer');
// so now, in your view you would have wether company with details wether an empty array
// *first line of code assumes parameter would be an integer
// **also assumed that $this->Company_model->get_company($id) would return false/null/anEmptyArray if data doesn't exist
}
I have ajax code that display the name of the cities(in selectbox) according the area that has been chosen:
<?PHP if ($_POST) { ?>
$(document).ready(function(){
$('#areaID').filter(function(){
var areaID=$('#areaID').val();
var cityID=<?PHP echo $cityID ?>;
$('#cityID').load('js/ajax/getCities.php?areaID=' + areaID+'&cityID=' + cityID);
return false;
});
});
<?PHP }else { ?>
$(function () {
function updateCitySelectBox() {
var areaID = $('#areaID').val();
$('#cityID').load('js/ajax/getCities.php?areaID=' + areaID);
return false;
}
updateCitySelectBox();
$('#areaID').change(updateCitySelectBox);
});
<?PHP } ?>
The problem is - after user submit the form and get error (i.e - forget to fill some field), user can change the area but the cities select box doesn't change according the new area.
What is wrong with the code?
<p><label>area</label>
<select name='areaID' id='areaID'>
<?PHP
$query = mysql_query("SELECT * FROM `areas` ORDER BY id ASC ");
while($index = mysql_fetch_array($query))
{
$db_area_id = $index['id'];
$db_area_name = $index['name'];
if ($db_area_id == $areaID)
echo "<option value='$db_area_id' selected>$db_area_name</option>";
else
echo "<option value='$db_area_id'>$db_area_name</option>";
}
?>
</select><span>*</span>
</p>
<p><label>City</label>
<select id='cityID' name='cityID'> </select>
</p>
I can't find the correct way update one row in my table.
My view:
...
<?php echo form_open('ImenikController/verify_editing_phonebook/'.$this->uri->segment(3)); ?>
Ime i prezime*:
<input type='text' name='ime_prezime' value=""> <br><br>
Ulica i broj: <input type='text' name='ulica' value=""> <br><br>
Mesto: <input type='text' name='mesto' value=""> <br><br>
Telefon*: <input type='text' name='telefon' value=""> <br><br>
<u>Napomena: Polja sa zvezdicom su obavezna.</u> <br /> <br />
<input background:url('images/login-btn.png') no-repeat; border: none;
width='103' height='42' style='margin-left:90px;' type='submit' value='Izmeni'>
<?php echo form_close(); ?>
...
My Controller:
function verify_editing_phonebook()
{
if ($this->session->userdata('logged_in'))
{
if ($this->session->userdata('admin') == 1)
{
$this->form_validation->set_rules('ime_prezime', 'Ime i prezime', 'trim|required|xss_clean');
$this->form_validation->set_rules('telefon', 'Telefon', 'trim|required|xss_clean');
if ($this->form_validation->run() == TRUE)
{
$id = $this->uri->segment(3);
if (isset($id) and $id > 0)
{
$this->load->model('LoginModel');
$this->LoginModel->edit_phonebook($id);
redirect(site_url().'ImenikController/', 'refresh');
}
}
else {
$temp = $this->session->userdata('logged_in');
$obj['id'] = $temp['id'];
$data['records'] = $this->LoginModel->get_Username($obj);
$this->load->view('ErrorEditing', $data);
}
}
else {
$this->load->view('restricted_admin');
}
}
else {
$this->load->view('restricted');
}
}
My Model:
function edit_phonebook($id)
{
$data = array ('ime_prezime' => $this->input->post('ime_prezime'),
'ulica' => $this->input->post('ulica'),
'mesto' => $this->input->post('mesto'),
'telefon' => $this->input->post('telefon'));
$this->db->where('id', $id);
$this->db->update('pregled', $data);
}
That solution doesn't work.
I get the url: localhost/imenik114/ImenikController/verify_editing_phonebook
It is a blank (white) page. And not editing row in table.
Basic Debugging Strategies
(1) Have you created all the view files?
(2) Have you tested edit_phonebook($id) independently?
(3) What does redirect(site_url().'ImenikController/', 'refresh'); display?
Did you define the index function for ImenikController?
(4) What URL did you use when you say 'That solution doesn't work.' ?
(5) If your URL is: "localhost/imenik114/ImenikController/verify_editing_phonebook"
you did not type in id in your 3rd segment
(6) If you are not logged in, do you see the correct restricted view?
(7) If you are logged in and NOT admin, do you see the correct restricted_admin view?
Potential Bug
Looking at this part of your code:
if ($this->form_validation->run() == TRUE)
{
$id = $this->uri->segment(3);
if (isset($id) and $id > 0)
{
$this->load->model('LoginModel');
$this->LoginModel->edit_phonebook($id);
redirect(site_url().'ImenikController/', 'refresh');
}
// You need to handle the case of $id not set
else
{
// load a view with error page saying $id is missing...
}
}
if your form validates, and you don't pass in segment(3), your controller will not load a view, therefore, you will get a blank page.
You need to check the case of $id not present, see code.
Code Fix
One more detail: the statement $id = $this->uri->segment(3); will set $id either to the id number or FALSE, therefore, you don't need isset($id) in your if statement. I would write $id = $this->uri->segment(3,0); to set the default to 0 instead of FALSE to keep the logic a bit clearer.
Thanks for answer but I solved my problem somehow.
I made a link in my view:
Edit
And in view for editing:
<?php echo form_open('Controller/verify_editing_phonebook/'.$this->uri->segment(3)); ?>
Function verify_editing_phonebook passed trough validation and loading view.
Thanks once again and sorry for my English...
1) I have a basic Joomla form that has three drop downs for Country, Town and Shop
2) I need to get the dropdown list based on the dropdown list provided above.
I have achieved to get the data from database and create drop down by coding in registration.xml in
usercomponent
What needs to be achieved:
I am trying to create dynamic drop downs based on the above data selected in the dropdown.
Please help me I am working hard for this I couldn't find the solution and code break through
I've created a basic non-Joomla example of this here
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<?php
$username = "USERNAME";
$password = "PASSWORD";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("DATABASE", $dbhandle) or die("Could not select examples");
$result = mysql_query("SELECT * FROM `values`");
$values=array();
$counter=0;
while($row = mysql_fetch_array($result))
{
$values[$counter]=$row{'country'};
$counter++;
}
mysql_close($con);
?>
<?php
$i=0;
$countries=array();
foreach($values as $value) {
$exists=false;
if(count($countries)>0) {
foreach($countries as $something) {
if($something==$value) {
$exists=true;
}
}
}
if($exists==false) {
$countries[$i]=$value;
$i++;
}
}
?>
<select id="first-choice">
<option selected value="base">Please Select</option>
<?php
$k=0;
while($k<count($countries)) {
echo "<option value='".$countries[$k]."'>" . $countries[$k] . "</option>";
$k++;
}
?>
</select>
<br />
<select id="second-choice">
<option>Please choose from above</option>
</select>
<br />
<select id="third-choice">
<option>Please choose from above</option>
</select>
<script type="text/javascript">
$("#first-choice").change(function() {
$("#second-choice").load("getter.php?country=" + $("#first-choice").val());
});
$("#second-choice").change(function() {
$("#third-choice").load("getter.php?town=" + $("#second-choice").val());
});
</script>
</body>
</html>
File called getter.php
<?php
$username = "USERNAME";
$password = "PASSWORD";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("DATABASE", $dbhandle) or die("Could not select examples");
if($_GET['country']) {
$countries = mysql_real_escape_string($_GET['country']);
$query = "SELECT * FROM `values` WHERE country='".$countries."'";
$result = mysql_query($query);
$values=array();
$i=0;
while($row = mysql_fetch_array($result))
{
$values[$i]=$row{'town'};
$i++;
}
$i=0;
$towns=array();
foreach($values as $value) {
$exists=false;
if(count($towns)>0) {
foreach($towns as $town) {
if($town==$value) {
$exists=true;
}
}
}
if($exists==false) {
$towns[$i]=$value;
$i++;
}
}
$k=0;
echo "<option selected value='base'>Please Select an Option</option>";
while ($k<count($towns)) {
echo "<option value=".$towns[$k].">" . $towns[$k] . "</option>";
$k++;
}
} elseif ($_GET['town']) {
$town = mysql_real_escape_string($_GET['town']);
$query = "SELECT * FROM `values` WHERE town='".$town."'";
$result = mysql_query($query);
echo "<option selected value='base'>Please Select an Option</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option>" . $row{'shop'} . "</option>";
}
}
?>
Based on the tutorial here. To Joomla this up. You will need to put the getter.php file into the model and call it through JSON (with a suitable controller). Remember to replace all visable text with JText - so it can be made with a language file. You also need to add the jquery into the header with JDocument::addScript or if your using Joomla 3.0 then JHtml::_('jquery.framework'); suffices. Also you must connect to the database through Joomla using JFactory::getDBO
I've put a basic example of this here.
Some notes: You may wish to call a specific version of JQuery as its constantly being updated. 1.9.0 works fine - but I don't know what will be hosted on that link when 2.0.0 comes out and what browser compatibility will be included.
This assumes a database structure of just
id country town shop. of course I doubt your database schemes are that easy. So remember to adapt this as necessary.
Hopefully this should start you going :)