This is My View Page
<select name="category" value="c_id" onChange="getsubcategorydetails(this.value)" style="display:">
<option value="" selected="selected" >Select Categories</option>
<?php if(isset($categories)) : foreach($categories as $row) :?>
<option value=<?php echo $row->c_id; ?>><?php echo $row->c_name; ?></option>
<?php endforeach;?>
<?php else :
endif;
?>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<tr>
<td>
<select name=" select id="subcategory">
<option value="" selected="selected" >Select Sub Category</option>
<?php foreach($sub_categories as $stt): ?>
<option value="<?php echo $stt->s_c_id; ?>"><?php echo $stt->s_c_name; ?></option>
<?php endforeach; ?>
</select>
</select></td>
</tr>
This is My Controller
public function getsubcategorydetails($c_id)
{
$c_id = $this->uri->segment(3);
// echo $c_id;
$data['sub_categories'] = $this->m_category->getsubcategorydetails($c_id);
//print_r($data['sub_category']);
$this->load->view('my_admin/newpost_1',$data);
}
This is My Model
function getsubcategorydetails($c_id='')
{
$this -> db -> select('*');
$this -> db -> where('c_id', $c_id);
$query = $this -> db -> get('subcategories');
return $query->result();
}
When i Click Category Select Box The Values returned from Controller ... But It Not Displayed On View ... What's Wrong With That .... Thanks In Advance
Here in my code,
iam posting categoryid through ajax in onchange event
and getting the subcategory for the categoryid from controller
and make the selection box in controller with the subcategory
and put the selection box in subcategory id.
Try this method.
View file
<select name="category" onChange="getsubcategorydetails(this.value)" >
<option value="" >Select Categories</option>
<?php if(isset($categories)) : foreach($categories as $row) :?>
<option value=<?php echo $row->c_id; ?>><?php echo $row->c_name; ?></option>
<?php endforeach;?>
<?php else :
endif;
?>
</select>
<select name="subcategory" id="subcategory">
<option value="" >Select Sub Category</option>
</select>
Controller
public function getsubcategorydetails($c_id)
{
$c_id = $this->input->post('c_id');
$sub_categories = $this->m_category->getsubcategorydetails($c_id);
$subcategory='<option value="" >Select Sub Category</option>';
foreach($sub_categories as $stt)
{
$subcategory.='<option value="'.$stt->s_c_id.'">'.$stt->s_c_name.'</option>';
}
echo $subcategory;
}
Model
function getsubcategorydetails($c_id='')
{
$this -> db -> select('*');
$this -> db -> where('c_id', $c_id);
$query = $this -> db -> get('subcategories');
return $query->result();
}
Script
function getsubcategorydetails(c_id)
{
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>yourcontroller/yourfunction",
data: {c_id:c_id},
success: function(data) {
$('#subcategory').html(data);
}
});
}
I suggest you to use JQuery AJAX to fetch the subcategory details.
Currently you are following wrong coding methods like calling a codeigniter controller function on an "OnChange" event with getsubcategorydetails($c_id) which is not right and makes it a wrong practice. OnChange event is used to call only Javascript functions.
To manipulate DOM, use Javascript/JQuery for it. Use the controller as a relay for getting appropriate formatted data into your JQuery.
Better option is Fetch data using AJAX and Append that to dependent select box onChange Event.
Related
I have a dropdown in which one is for states and second one is it's sub category, which shows name of cities on basis of first dropdown.
Right now user need to select one category then subcategories load,
What change I want is "To set one value as default and load it's subcategories too" at load of page, and further user select different category so it should load it's subcategories accordingly.
Index.php:
<form name="insert" action="" method="post">
<table width="100%" height="117" border="0">
<tr>
<th width="27%" height="63" scope="row">Sate :</th>
<td width="73%">
<select onChange="getdistrict(this.value);" name="state" id="state" class="form-control">
<option value="">Select</option>
<?php $query =
mysqli_query($con,"SELECT * FROM state");
while($row=mysqli_fetch_array($query))
{ ?>
<option value="<?php echo $row['StCode'];?>">
<?php echo $row['StateName'];?>
</option>
<?php }?>
</select>
</td>
</tr><tr>
<th scope="row">District :</th>
<td>
<select name="district" id="district-list" class="form-control">
<option value="">Select</option>
</select>
</td>
</tr>
</table>
</form>
<script>
function getdistrict(val) {
$.ajax({
type: "POST",
url: "get_district.php",
data: "state_id=" + val,
success: function (data) {
$("#district-list").html(data);
},
});
}
</script>
get_district.php:
<?php
require_once("config.php");
if(!empty($_POST["state_id"])){
$query =mysqli_query($con,"SELECT * FROM district WHERE StCode = '" . $_POST["state_id"] . "'");
?>
<option value="">Select District</option>
<?php
while($row=mysqli_fetch_array($query)){
?>
<option value="<?php echo $row["DistrictName"]; ?>"><?php echo $row["DistrictName"]; ?></option>
<?php
}
}
?>
You would need to do 2 things
1.) insert a selected flag into the input
2.) activate the second dropdown on page load
1.) If the selected entry does never change then hardcode the default selected field in your code like if $var = XXX then echo "selected".
If you have any function which calculates the default value e.g. a geolocation service like e.g. maxmind.com which takes the users remote IP address and outputs his current state, then use this result to set the selected entry.
<?php
while($row=mysqli_fetch_array($query)){
$row["StCode"] == "DESIRED_VALUE" ? $selected ="selected" : $selected ="";
?>
<option value="<?php echo $row['StCode'];?>" <?= $selected ?> ><?php echo $row['StateName'];?>
</option>
[...]
Or add a field in the table SELECTED where you mark the default record with 1.
<?php
while($row=mysqli_fetch_array($query)){
$row["selected"] == 1 ? $selected ="selected" : $selected ="";
?>
<option value="<?php echo $row['StCode'];?>" <?= $selected ?> >
<?php echo $row['StateName'];?>
</option>
[...]
2.) You have to set the second select dropdown on page load. There are several ways to do this - this is explained here in detail:
Jquery execute onchange event on onload
I am creating a simple form with fields like First_name, Last_name, city etc.So for city field, I want to display dynamic data.Below is the code I am using it's in PHP CodeIgniter.
Controller Page:
public function city()
{
$this->load->model('dropdownM');
$getcity=$this->dropdownM->get_city();
$this->load->view('form1city',$getcity);
}
Model Page:
<?php
class DropdownM extends CI_Model
{
public function get_city()
{
$this->db->select('fname');
$this->db->from('city');
$query = $this->db->get();
if($query->num_rows()>0)
{
return $query->result();
}
}
}
View page:
<form action="<?php echo base_url(); ?>index.php/Rec/user" method="post">
<select class="form-control" id="city" name="city">
<option value="">Select </option>
<?php if(count($getcity)):?>
<?php foreach($getcity as $city):?>
<option value=<?php echo $city->c_id;?>><?php echo $village1->C_name;?></option>
<?php endforeach;?>
<?php else:?>
<?php endif;?>
</select>
<center>
<input type="submit" value="Submit" class="btn btn-bricky" id="subbtn"
name="submit1">
</center>
<form>
It's not displaying anything in the drop-down.I am not able to find out what the issue.
pass data like this
$data['getcity']=$this->dropdownM->get_city();
$this->load->view('form1city',$data);
and in view
<?php if(count($getcity) > 0):?>
<select class="form-control" id="city" name="city">
<option value="">Select </option>
<?php foreach($getcity as $city):?>
<option value=<?php echo $city['c_id'];?>><?php echo $village1['C_name'];?></option>
<?php endforeach;?>
</select>
<?php else:?>
<p>No Category Found</p>
<?php endif;?>
In model
$this->db->select('fname');
$this->db->from('city');
$query = $this->db->get();
return $query->result_array();
in a web form there are two drop-down lists. The second list items should change dynamically depending on the value selected on the first drop-down list.
This is how am I trying to do it:
index.php:
...
<script>
function getClient(val) {
$.ajax({
type: "POST",
url: "get_contacts.php",
data:'client_id='+val,
success: function(data){
$("#contacts-list").html(data);
}
});
}
</script>
...
<div class="form-group">
<label for="mto_client" class="col-sm-2 control-label">MTO Client</label>
<div class="col-sm-10">
<select name="mto_client" id="clients_list" onChange="getClient(this.value)">
<option value="">Select a Client</option>
<?php
do {
?>
<option value="<?php echo $row_RSClients['id_client']?>" ><?php echo $row_RSClients['client_name']?></option>
<?php
} while ($row_RSClients = mysql_fetch_assoc($RSClients));
?>
</select>
</div>
</div>
<div class="form-group">
<label for="mto_client_contact" class="col-sm-2 control-label">MTO Client Contact</label>
<div class="col-sm-10">
<select name="state" id="contacts-list">
<option value="">Select Client Contact</option>
</select>
</div>
</div>
get_contacts.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["client_id"])) {
$query ="SELECT * FROM tb_client_contacts WHERE contact_client_id = '" . $_POST["client_id"] . "'";
$results = $db_handle->runQuery($query);
?>
<option value="">Select Client Contact</option>
<?php
foreach($results as $state) {
?>
<option value="<?php echo $state["id_client_contact"]; ?>"><?php echo $state["contact_name"]; ?></option>
<?php
}
}
?>
There are objects on the table tb_clients_contact that meet the condition, but the second drop-down list doesn't show any objects.
Any help is welcome.
Instead of
$("#contacts-list").html(data);
It should be
$('#contacts-list').empty().append(data);
empty() will clear first the options inside the contacts-list select field, then append() will insert the options from the result of your AJAX.
You can also look at the console log for errors. If you are using Google Chrome, hit F12 to display the console log.
I have a little problem.
I'm searching the internet now for quite some time to find a proper solution but I was not successful so far.
This is what I want :
First, I choose Category
Then, in second selection contain all the store result from category selection.
this is my first drop down list which is contain Category :
<select name="category" class="form-control" id="select1">
<option value="-1"> - Choose One -</option>
<?php
$StoreCategoriesAPIAccessor = new StoreCategoriesAPIService(GuzzleClient::getClient());
$stores = $StoreCategoriesAPIAccessor->getStoreCategories();
foreach ($stores as $store):
?>
<option value="<?php echo $store->getStoreCategoryId(); ?>"><?php echo $store->getCategory(); ?></option>
<?php endforeach; ?>
</select>
this is my second drop down list :
<select name="category" class="form-control" id="select2">
<option value="-1"> - Choose One -</option>
<?php
$StoreAPIAccessor = new StoreAPIService(GuzzleClient::getClient());
$stores = $StoreAPIAccessor->getStores();
foreach ($stores as $store):
?>
<option value="<?php echo $store->getStoreId(); ?>"><?php echo $store->getStoreName(); ?></option>
<?php endforeach; ?>
</select>
Anyone know how to implement dynamic drop down list for this case ?
Well first of all I'd like to ask that you separate business logic from view logic as much as possible, so I will do that in this answer.
Secondly, the 2nd dropdown box logic that you have does not contain anything that would retrieve stores for a given category, I will therefore make some assumptions and you can adjust based on that.
<?php
$StoreCategoriesAPIAccessor = new StoreCategoriesAPIService(GuzzleClient::getClient());
$categories = $StoreCategoriesAPIAccessor->getStoreCategories();
if (!empty($_GET['category'])) {
$category_id = $_GET['category'];
$StoreAPIAccessor = new StoreAPIService(GuzzleClient::getClient());
$stores = $StoreAPIAccessor->getStores($category_id); // Assumption, the call to getStores() accepts category_id as a parameter
} else { // Optional as you don't need to declare variables in PHP, but its better practice to do so
$category_id = null;
$stores = array();
}
?>
<select id="select_category" name="category" class="form-control" onchange="window.location='?category=' + this.value">
<option value="">- Choose One -</option>
<?php foreach ($categories as $category): ?>
<option value="<?php echo $category->getStoreCategoryId() ?>"><?php echo $category->getCategory() ?></option>
<?php endforeach ?>
</select>
<select id="select_store" name="store" class="form-control"<?php echo $category_id == null ? " disabled='disabled'" : "">
<option value="">- Choose One -</option>
<?php foreach ($stores as $store): ?>
<option value="<?php echo $store->getStoreId() ?>"><?php echo $store->getStoreName() ?></option>
<?php endforeach ?>
</select>
I have 2 select's inside a form. The second select has about 2000 lines in total coming out of my mysql table. One of the column into that mysql has 1 of the values used into the first select. I want to be able to filter on that value when it is selected into the first select, so that it only shows these articles.
code now:
<div class="rmaform">
<select name="discipline" class="discipline">
<option value=" " selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article">
<?php
$articleselect = $dbh->prepare('SELECT * FROM articles');
$articleselect->execute();
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
</select>
I think i have to use Javascript for it but how do you combine PHP and Javascript? And what would be the best way to make the filter work?
jQuery for the change event and AJAX
$(document).ready(function(e) {
$('select.discipline').change(function(e) { // When the select is changed
var sel_value=$(this).val(); // Get the chosen value
$.ajax(
{
type: "POST",
url: "ajax.php", // The new PHP page which will get the option value, process it and return the possible options for second select
data: {selected_option: sel_value}, // Send the slected option to the PHP page
dataType:"HTML",
success: function(data)
{
$('select.input-article').append(data); // Append the possible values to the second select
}
});
});
});
In your AJAX.php
<?php
if(isset($_POST['selected_option']))
$selected_option=filter_input(INPUT_POST, "selected_option", FILTER_SANITIZE_STRING);
else exit(); // No value is sent
$query="SELECT * FROM articles WHERE discipline='$selected_option'"; // Just an example. Build the query as per your logic
// Process your query
$options="";
while($query->fetch()) // For simplicity. Proceed with your PDO
{
$options.="<option value='option_value'>Text for the Option</option>"; // Where option_value will be the value for you option and Text for the Option is the text displayed for the particular option
}
echo $options;
?>
Note: You can also use JSON instead of HTML for much simplicity. Read here, how to.
First give both of the selects an unique ids...
<div class="rmaform">
<select name="discipline" class="discipline" id="discipline">
<option value="" selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article" id="article">
<option value="" selected></option>
</select>
Now you can use jQuery Ajax call to another file and get the HTML Response from that file and Populate in the select field with id="article" like this...
<script type="text/javascript">
$(document).ready(function(){
$("#discipline").change(function(){
var discipline = $(this).val();
$.post(
"ajax_load_articles.php",
{discipline : discipline},
function(data){
$("#article").html(data);
}
)
});
});
</script>
Now create a new file like ajax_load_articles.php... in the same directory where the html file exists... You can place it anywhere but then you have to change the $.post("url", the url to the ajax submission.
Contents of ajax_load_articles.php :
<?php
$discipline = $_POST["discipline"];
$articleselect = $dbh->prepare("SELECT * FROM articles WHERE colname = '{$discipline}'");
$articleselect->execute();
echo '<option value="" selected></option>';
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
Now when ever you will change the select of the first select field an Ajax call will take place and the data of the second select field will automatically adjust to related data selected in the first select field.
This is an example where you can select the college specific to the state ..
Form.php
// your code for form ...
// select box for state starts
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">State</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="statename" id="stateid">
<option value="">---- Select ----</option>
<?php
$state=sql::readResultArray("Your Query To select State`");
foreach($state as $s){
?>
<option value="<?php echo $s?>"> <?php echo $s ?> </option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">Colleges</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="mycollegename">
<option value="">--- Select --- </option>
</select>
</div>
</div>
// further code for from in form.php..
Script to find the state and then pass the value to find the respective colleges in that state
<script>
$(document).ready(function(e) {
$('#stateid').change(function()
{ ids=$('#stateid').val();
$.get('mycollege.php', {type:ids} ,function(msg){
$('select[name="mycollegename"]').html(msg);
});
});
});
</script>
Call this file through ajax .. Code on this file
mycollege.php
<?php
require('db.php'); // call all function required, db files or any crud files
$type=$_GET['type'];
if(!empty($type)){
$r=sql::read("Your Query To call all teh college list");
?>
<select name="mycollegename">
<option value="">Select One</option>
<?php
foreach($r as $r){
echo "<option value=\"$r->collegename\">$r->collegename </option>";
}
?>
</select>
<?php }else{ ?>
<select name="mycollegename">
<option value="">Select State</option>
</select>
<?php } ?>