Create subcategory select box onChange - javascript

I am creating a category system where users can select category from DB and after they select it creates another select box with subcategory of that category.
So, my question is how can I do it the best way?
BTW I am using Laravel Framework and first category is simple
<select>
#foreach(Category::all() as $k)
<option value="{{ $k['id'] }}">{{ $k['name'] }}</option>
#endforeach
</select>
But what should I do after they pick a category? Is it better to do the AJAX call to send the ID of picked category and returns the subcategory or what?
I need the best and professional way to do this.
In my Database I have
ID, name, parent

Use ajax, after selecting the category send the ajax request and to do this you need to use change event on your select, for example:
// Assumed category is id of the select
$('#category').on('change', function(){
var id = $(this).val();
$.getJSON("subcategory/" + id , function(data){
// Assumed subcategory is id of another select
var subcat = $('#subcategory').empty();
$.each(data, function(k, v){
var option = $('<option/>', {id:k, value});
subcat.append(option);
});
});
});
On the server side, create a route like this (You may use a controller and Eloquent):
Route('subcategory/{id}', function($id){
// Get the data from database according to the id
// Build an array as: id => value and then return
return Response::json($subcat);
});

Populate a dropdown on selecting an option from another dropdown Laravel
This might surely help you. Otherwise ask if you do not understand

select_cat.php
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".category").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "select_subcat.php",
data: dataString,
cache: false,
success: function(html)
{
$(".subcat").html(html);
}
});
});
});
</script>
Category :
<select name="category" class="category">
<option selected="selected">--Select Category--</option>
<?php
include('databasefile');
mysql_connect($server,$username,$password)or die(mysql_error());
mysql_select_db($database)or die(mysql_error());
$sql=mysql_query("select cat_name from category order by cat_name");
while($row=mysql_fetch_array($sql))
{
$cname=$row['cat_name'];
echo '<option value="'.$cname.'">'.$cname.'</option>';
} ?>
</select> <br/><br/>
SubCategory :
<select name="subcat" class="subcat">
<option selected="selected">--Select SubCat--</option>
</select>
2.select_subcat.php
<?php
include('databasefile);
mysql_connect($server,$username,$password)or die(mysql_error());
mysql_select_db($database)or die(mysql_error());
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysql_query("select s_name from subcat_l1 where cat_name='$id'");
while($row=mysql_fetch_array($sql))
{
$sname=$row['s_name'];
echo '<option value="'.$sname.'">'.$sname.'</option>';
}
}
?>
SubCategory :
<select name="subcat" class="subcat">
<option selected="selected">--Select SubCat--</option>
</select>

Related

PHP/Jquery issue populating 3 dynamic select boxes

I am quite new to PHP and JQuery and am struggling with 3 dynamic select boxes. The first one should contain a list of my instruments. The second one a list of categories, and the third should contain a list of subcategories, based on the selected value of the category and selected instrument. Have followed some great tutorials on the matter, but none seem exactly what I need. So far, managed to populate the instruments and the categories select box correctly, but when clicking on the categories select box to select the value I want, it malfunctions, the subcategories box stay empty. I believe the problem is because I do not send the instrumentID correctly when the categories onchange occurs, but cannot seem to find how to properly send it. Can anyone help me please ?
This is my code so far :
<?php
$query = "SELECT * FROM instruments ORDER BY name ASC";
$result = $db->query($query)->results();
?>
<div class = "form-group col-md-3>"
<select name="instrument_id" id="instrument_id">
<option value="">-Select Instrument-</option>
<?php
foreach($result as $row){
echo '<option value="'.$row->id.'">'.$row->name.'</option>';
}
?>
</select>
</div>
<div class="form-group col-md-3">
<label for="category_id" class="control-label">Category</label>
<select id="category_id" name="category_id" class="form-control input-sm">
<option value="">-Select Category-</option>
</select>
</div>
<div class="form-group col-md-3">
<label for="subcategory_id" class="control-label">Subcategory</label>
<select id="subcategory_id" name="subcategory_id" class="form-control input-sm">
<option value="">-Select Subcategory-</option>
</select>
</div>
<script>
$(document).ready(function(){
$('#instrument_id').on('change', function(){
const instrumentID = $(this).val();
if(instrumentID){
$.ajax({
type:'POST',
url:'<?=PROOT?>admindocuments/get_categories',
data:{instrument_id: instrumentID},
success:function(html){
$('#category_id').html(html);
$('#subcategory_id').html('<option value="">-Select Subcategory-</option>');
}
});
}else{
$('#category_id').html('<option value="">-Select Category- </option>');
$('#subcategory_id').html('<option value="">-Select Subcategory- </option>');
}
});
$('#category_id').on('change', function(){
const categoryID = $(this).val();
const instrumentID = $('#instrument_id').val();
if(categoryID){
$.ajax({
type:'POST',
url:'<?=PROOT?>admindocuments/get_subcategories',
data: {
category_id: categoryID,
instrument_id: instrumentID,
},
success:function(html){
$('#subcategory_id').html(html);
}
});
}else{
$('#subcategory_id').html('<option value="">-Select Subcategory- </option>');
}
});
});
</script>
And this is the code in my get_categories.php and get_subcategories.php file :
get_categories :
<?php
if($_POST["instrument_id"]){
$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query)->results();
echo '<option value="">-Select Category-</option>';
foreach($result as $row){
echo '<option value="'.$row->id.'">'.$row->name.'</option>';
}
}
?>
get_subcategories :
<?php
if($_POST["category_id"] && !empty($_POST["instrument_id"])){
$query = "SELECT * FROM subcategories WHERE category_id = ".$_POST['category_id']." AND instrument_id = ".$_POST['instrument_id']." ORDER BY name ASC";
$result = $db->query($query)->results();
echo '<option value="">-Select Subcategory-</option>';
foreach($result as $row){
echo '<option value="'.$row->id.'">'.$row->name.'</option>';
}
}
What am I doing wrong ? Please help me.
Kind regards
The root of your problem is that you aren't sending the instrument id at all when getting subcategories. First you need to fetch it in your handler, since your select has an id, it's easy:
$('#category_id').on('change', function(){
const categoryID = $(this).val(); // I changed var to const here, read more about it below
const instrumentID = $('#instrument_id').val(); // this line added
Here you can read about using const and let over var.
And then you need to send it in AJAX data:
// sending it as an object is more readable and PHP reads it just the same
data: {
category_id: categoryID,
instrument_id: instrumentID,
}
Now you also need to fix your PHP side. As it currently stands, if you send this kind of data, your first branch would be activated because instrument id is set in both cases:
if (!empty($_POST["instrument_id"])) {
// get categories
} elseif(!empty($_POST["category_id"])) {
// get subcategories
}
What you should be checking for instead is if both parameters are set (that's how you determine you need subcategories):
if (!empty($_POST["instrument_id"]) && !empty($_POST["category_id"])) {
// get subcategories
} elseif (!empty($_POST["category_id"]) && empty($_POST["instrument_id"])) {
// get categories
}
But a much cleaner solution would be to simply have two PHP scripts, one for categories and one for subcategories. Then you wouldn't need this complex if-elseif structure and your tasks would be logically separated (currently, you're using a file called get_subcategories to get both subcategories and categories, so it isn't really aptly named).
Another thing you should avoid at all costs is building queries by directly inserting parameters:
$query = "SELECT * FROM subcategories WHERE category_id = ".$_POST['category_id']." AND instrument_id = ".$_POST['instrument_id']." ORDER BY name ASC";
This kind of practice leaves you wide open to SQL injection. You should use prepared statements instead.

How to display the state and city name from the database on edit page?

I am fetching data from the database in the edit page.
I am using CodeIgniter, I have two view pages, register, and edit_register.
I don't have any issue on register page but still, I am sharing the process to understand my issue. On this page country, state, city dependancy is also working. I mean I choose "India" then It will display all state name in state dropdown. Now I choose "Maharashtra" then I choose "Mumbai". Working perfectly.
I submitted the form and in the database, I am getting the value like
Country_name | state_name | city
101 | 22 | 2707
--------------------------------------
101-India
22-Maharashtra
2707-Mumbai
Let's talk about edit_register page.
Now I am on the edit_register page, I am fetching the country name in the dropdown. I am getting the correct output "India" but I am not getting the state and city name.
So my issue is how to display the state and city name from the database?
Please check this when I click on edit button then I am getting only the country name but state name not displaying.
If I choose other country and again choose India then I am getting all the state name in the drop-down.
Controller
It's displaying my edit page with country name in the drop-down
public function search_with_number(){
$c_mobileno=$this->input->post('c_mobileno_search');
$got_customer_info['search_customer_info']=$this->Customer_model->get_customer_info($c_mobileno);
$got_customer_info['get_country']=$this->Customer_model->get_country();// all country name
$this->load->view('customer/search_order',$got_customer_info);
}
Country drop-down It's working.
<select class="form_control country_change" name="c_s_country" data-target="target_state_dropdown2">
<option value="" disabled selected>Select Country</option>
<?php foreach ($get_country as $row) {?>
<option <?php if($row->id == $post->c_s_country ){ echo 'selected="selected"'; } ?> value="<?php echo $row->id; ?>"><?php echo $row->country_name;?></option>
<?php }?>
</select>
State drop-down It's not working
<select class="form_control state_get" name="c_s_state" id="target_state_dropdown2" data-target="city_dropdown2">
<option value='' disabled selected>Select state</option>
<!--What code I have to user here-->
</select>
City It's not working
<select class="form_control city_get" name="c_s_city" id="city_dropdown2">
<option value="" disabled selected>Select city </option>
<!--What code I have to user here-->
</select>
Ajax which I am using in register page
/*Get all the state name using country code*/
$(".country_change").on('change',function(){
var country_id=$(this).val();
var select_list = $(this).data('target'); // The dropdown ID
$.ajax({
url:baseUrl +"/Customer_control/statename",
method:"POST",
data:"country_id="+country_id,
dataType: "json",
success:function(data){
$('#'+select_list).empty();
var placeholder="<option value='' disabled selected>Select state</option>";
$('#'+select_list).html(placeholder);
$.each(data, function(i, data) {
$('#'+select_list).append("<option value='" + data.id + "'>" + data.state_name + "</option>");
});
}
});
});
/*Get all the city name using state code*/
$(".state_get").on('change',function(){
var state_id=$(this).val();
var select_list = $(this).data('target'); // The dropdown ID
$.ajax({
url:baseUrl +"/Customer_control/cityname",
method:"POST",
data:"state_id="+state_id,
dataType: "json",
success:function(data){
$('#'+select_list).empty();
var placeholder="<option value='' disabled selected>Select city</option><option value='Other'>Other</option>";
$('#'+select_list).html(placeholder);
$.each(data, function(i, data) {
$('#'+select_list).append("<option value='" + data.id + "'>" + data.cities_name + "</option>");
});
}
});
});
State model
public function get_country()
{
$get_country = array('is_country_active' => 1);
$this->db->where($get_country);
$query = $this->db->get('countries');
$result = $query->result();
if($result)
{
return $result;
}
else
{
return 0;
}
}
public function get_state($country_id){
$get_state = array('is_state_active' => 1,'country_id'=>$country_id);
$this->db->where($get_state);
$query = $this->db->get('states');
$result = $query->result();
if($result)
{
return $result;
}
else
{
return 0;
}
}
public function get_city($state_id){
$get_city = array('is_city_active' => 1,'state_id'=>$state_id);
$this->db->where($get_city);
$query = $this->db->get('cities');
$result = $query->result();
if($result)
{
return $result;
}
else
{
return 0;
}
}
I haven't added the city JS.
Now Please check my Ajax code, My state name is changing when I select a country name. I have to display the state and city name onload from the database
In edit view, you need to do the same as you did for country. First of all, you need to fetch all your state and city from db.
Also you need to store state_id and city_id in db if you are not storing it during creation.
Now you need to pass those data to your edit view and do the same as you did for the country like this:-
<select name = "state">
<option value="">Choose State</option>
<?php foreach($state as $row){ ?>
<option value="<?php echo $row->state_id; ?>" <?php if($row->state_id == $selected->state_id){ echo "SELECTED";} ?>> <?php echo $row->state_id; ?></option>
<?php } ?>
</select>
Do the same thing for city also. Please also remember you need to execute ajax at edit page also if the user changes the city.
This should be the code on the controller:-
public function search_with_number(){
$c_mobileno=$this->input->post('c_mobileno_search');
$got_customer_info['search_customer_info']=$this->Customer_model-
>get_customer_info($c_mobileno); //get here your saved state id of this user and match it in the view level
$got_customer_info['get_country']=$this->Customer_model->get_country();// all country name;
$got_customer_info['get_state']=$this->State_model->get_state();// all state name;
$this->load->view('customer/search_order',$got_customer_info);
}

How to populate a dropdown with AJAX

I want to populate a dropdown (AJAX) when I click on the dropdown.
I have a dropdown categories and a button Add categories
When I open the page the first time, I can see my categories inside the dropdown.
If I want to include another categories, I click on Add categories and I insert my new categories.
After, if I click on the dropdown, I must see my new categories.
How to do that ?
I don't know exactly how to create that.
Thank you
my_ajax_file.php
$Qcheck = $OSCOM_Db->prepare('select categories_id as id,
categories_name as name
from :table_categories');
$Qcheck->execute();
$list = $Qcheck->rowCount();
if ($list > 0) {
$array = [];
while ($value = $Qcheck->fetch() ) {
$array[] = $value;
}
# JSON-encode the response
$json_response = json_encode($array); //Return the JSON Array
# Return the response
echo $json_response;
HTML code
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
}
});
});
}
</script>
<select name="category_id" id="Mycategory_id" class="form-control">
<option value="0" selected="selected">Haut</option>
<option value="23">Panneaux Signalétique</option>
<option value="20">Signalétique Camping</option>
<option value="22"> Barrières</option>
<option value="21"> Entrée</option>
</select>
<input type="hidden" name="current_category_id" value="0" /></div>
You need to update the select element with new options.
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
var options_html = '';
for(index in data){
var category_id = data[index]['categories_id'];
var category_name = data[index]['categories_name'];
options_html += '<option value="'+category_id+'">' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
)};
</script>
To make rendering easy, you can use mustache.js

dependent dropdown with jquery CODEIGNITER previous selection does not go away

I have this dependent dropdown working initially, but after the second selection the values of the first selection do not go away. Instead, the new values are just mixed with the previous values. I'm not familiar with jQuery but I need to finish this one as soon as possible.
first dropdown
<select class="form-control" name = "PROV_ID" id = "PROV_ID">
<option></option>
<?php foreach ($content as $cs) {?>
<option value="<?php echo $cs->PROV_ID; ?>"><?php echo $cs->PROVINCE; ?></option>
<?php } ?>
</select>
second dropdown
<select name = 'CT_ID' id = 'CT_ID'>
<option value="">-- Select Type --</option>
</select>
jquery
<script>
jQuery(document).ready(function(){
$("#PROV_ID").change(function() {
var PROVID = {"PROVID" : $('#PROV_ID').val()};
console.log(PROVID);
$.ajax({
type: "POST",
data: PROVID,
url: "<?php base_url(); ?>Employees/dependent_dropdown",
success: function(data){
$.each(data, function(i, data){
$('#CT_ID').append("<option value='"+data.CT_ID+"'>"+data.CITY+"</option>");
});
}
});
});
});
</script>
I want to refresh the value of the second dropdown whenever I select a new option on the first dropdown.
Clear the existing options before appending:
success: function(data){
var select = $('#CT_ID');
select.empty();
$.each(data, function(i, option){
select.append("<option value='"+option.CT_ID+"'>"+option.CITY+"</option>");
});
}
This is because you are using append to add HTML to the select element. I would suggest using jQuery's html to set the HTML of the select (which will clear any existing option elements). The added benefit here is that you are only doing one DOM manipulation, as opposed to one per option.
success: function(data){
var $select = $('#CT_ID'),
html = '';
$.each(data, function(i, option) {
html += "<option value='"+option.CT_ID+"'>"+option.CITY+"</option>";
});
$select.html(html);
}

Change items in a drop-down list depending on the selected option in another drop-down list

I have the following code:
<select name="trec">
<? $d -> gettreatment(); ?>
</select>
<select name="treratment">
<? $d -> gettreat(); ?>
</select>
the <? $d -> gettreatment(); ?>
will display echo "<option value='$r[id]'>$r[cat]</option>";
and <? $d -> gettreat(); ?>
will display echo "<option value='$r[id]'>$r[treatment]</option>";
How to dynamically narrow down (or limit) the items in a second drop down list based on the selected item from first selected item? For example if we have one list of countries in first drop down list and have list of states in the second list then once USA is selected from the country list then the second list should change to list only the states of USA
<script type="text/javascript">
$(function() {
$("#form_process").click(function() {
//$("#choice").val(); //you cannot use the same id for more than 1 tag
var choice = 0;
if(document.getElementById("choice1").checked) choice='Yes';
else if(document.getElementById("choice2").checked) choice='No';
else if(document.getElementById("choice3").checked) choice='Dont Know';
var comments = document.getElementById('comments').value; //$("#comments").val();
var dataString = 'choice='+ choice + '&comments=' + comments;
$.ajax({
type: "POST",
url: "**ABSOLUTE URL TO PROCESSOR**",
data: dataString
});
});
});
</script>

Categories

Resources