JQuery Dynamic Option Select Issue - javascript

This is the continution of this Question
Here is the Code for Dynamic JQuery Option Select Generator.
First i will choose the Country, which i didn't include the code, it will return the CountryID which is passed to the controller, then RegionID, then CityID. IT works well until generating the CityID Option select Menu, while i move to the AreaID it didn't work.
What i am missing and how can i fix that ?
I can't able to generate the Menu after the third Second One.
Here is the HTML :
<div id='result' name="result">
<select id="name">
<option value="" disabled>Please select above</option>
</select>
</div>
<div id='resulta' name="resulta">
<select id="name">
<option value="" disabled>Please select above</option>
</select>
</div>
<div id='resultb' name="resultb">
<select id="name">
<option value="" disabled>Please select above</option>
</select>
Here is my Script :
<script>
var ab = $.noConflict();
ab(document).ready(function() {
ab(document).on("change", "#CountryID", function() {
var CountryID = ab("#CountryID").val();
ab.post("globalregiongenerator", {
CountryID: CountryID
},
function(data) {
ab("#result").html(data);
});
});
});
</script>
<script>
var ac = $.noConflict();
ac(document).ready(function() {
ac(document).on("change", "#RegionName", function() {
var RegionName = ac("#RegionName").val();
ac.post("globalcitygenerator", {
RegionName: RegionName
},
function(data) {
ac("#resulta").html(data);
});
});
});
</script>
<script>
var ad = $.noConflict();
ad(document).ready(function() {
ad(document).on("change", "#CityName", function() {
var CityName = ad("#CityName").val();
ad.post("globalareagenerator", {
CityName: CityName
},
function(data) {
ad("#resultb").html(data);
});
});
});
</script>
And here is the Server Side :
public function globalregiongenerator()
{
$CountryID = Input::get('CountryID');
$result = DB::select("SELECT * FROM region where CountryID =$CountryID");
echo "<select id='RegionName' name='RegionName'> <option value='' id=''>Select the Area</option>";
foreach ($result as $value)
{
echo "<option value=".$value->RegionID.">".$value->RegionName."</option>";
}
echo "</select>";
}
public function globalcitygenerator()
{
$RegionID = Input::get('RegionName');
$result = DB::select("SELECT * FROM city where RegionID =$RegionID");
echo "<select id='CityName' name='CityName'> <option value='' id=''>Select the Area</option>";
foreach ($result as $value)
{
echo "<option value=".$value->CityID.">".$value->CityName."</option>";
}
echo "</select>";
}
public function globalareagenerator()
{
$CityID = Input::get('CityName');
$result = DB::select("SELECT * FROM area where CityID =$CityID");
echo "<select id='CityName' name='CityName'> <option value='' id=''>Select the Area</option>";
foreach ($result as $value)
{
echo "<option value=".$value->CityID.">".$value->CityName."</option>";
}
echo "</select>";
}
Note :
Uncaught TypeError: undefined is not a function
This is the error i got in console

Change
echo "<option value=".$value->CityID.">".$value->CityName."</option>";
to
echo "<option value='".$value->CityID."'>".$value->CityName."</option>";
Same with other echos. You're generating
<option value=united states>United States</option>
but it needs to be
<option value='united states'>United States</option>
Update:
Change them to
echo "<option value=\"".$value->CityID."\">".$value->CityName."</option>";

Related

Show Hide label based on select drop down values

I want to Hide and Show the "City" label.
Show only if I choose specific "State" if not hide it again.
Country=USA> State=Texas> Show the City label.
Country=USA> State=New York> Hide the City label
$(document).ready(function() {
// Country dependent ajax
$("#country").on("change", function() {
var countryId = $(this).val();
$.ajax({
url: "action.php",
type: "POST",
cache: false,
data: {
countryId: countryId
},
success: function(data) {
$("#state").html(data);
$('#city').html('<option value="">Select city</option>');
}
});
});
// state dependent ajax
$("#state").on("change", function() {
var stateId = $(this).val();
$.ajax({
url: "action.php",
type: "POST",
cache: false,
data: {
stateId: stateId
},
success: function(data) {
$("#city").html(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post">
<div class="col-md-4">
<!-- Country dropdown -->
<label for="country">Country</label>
<select class="form-control" id="country">
<option value="">Select Country</option>
<?php
$query = "SELECT * FROM countries";
$result = $con->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['id'].'">'.$row['country_name'].'</option>';
}
}else{
echo '<option value="">Country not available</option>';
}
?>
</select>
<br />
<!-- State dropdown -->
<label for="country">State</label>
<select class="form-control" id="state">
<option value="">Select State</option>
</select>
<br />
<!-- City dropdown -->
<label for="country">City</label>
<select class="form-control" id="city">
<option value="">Select City</option>
</select>
</div>
</form>
</div>
Action.php
<?php
// Include the database connection file
include('db_config.php');
if (isset($_POST['countryId']) && !empty($_POST['countryId'])) {
// Fetch state name base on country id
$query = "SELECT * FROM states WHERE country_id = ".$_POST['countryId'];
$result = $con->query($query);
if ($result->num_rows > 0) {
echo '<option value="">Select State</option>';
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['id'].'">'.$row['state_name'].'</option>';
}
} else {
echo '<option value="">State not available</option>';
}
} elseif(isset($_POST['stateId']) && !empty($_POST['stateId'])) {
// Fetch city name base on state id
$query = "SELECT * FROM cities WHERE state_id = ".$_POST['stateId'];
$result = $con->query($query);
if ($result->num_rows > 0) {
echo '<option value="">Select city</option>';
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['id'].'">'.$row['city_name'].'</option>';
}
} else {
echo '<option value="">City not available</option>';
}
}
?>
try to add a condition inside the success callback function of the state dependent ajax request
success: function(data) {
$("#city").html(data);
if ($("#state").val() === "Texas") {
$("#city").parent().prev("label[for='country']").show();
} else {
$("#city").parent().prev("label[for='country']").hide();
}
}
It would be easier if the label was wrapping the select or the label and select was inside a div but here you are
You could just test the state since I expect you do not have other countries with a state called Texas
This goes anywhere
$("form").on("change", "select", function() {
const country = $("#country").val();
const state = $("#state").val();
const show = country === "USA" && state === "Texas";
$("$city").toggle(show);
$("$city").prev().toggle(show); // label
})

AJAX not triggering preset function using PDO to retrieve from database

Having this part in an HTML form, working in PHP for server-side backend. Need the user to select country and based on the country the city list is refined to that particular country cities only. AJAX is refreshing and passing the variables but the PHP function is not triggering:
// PHP part
$action = "all";
if (isset($_POST['action'])) {
$action = $_POST['action'];
}
if (isset($_GET['action'])) {
$action = $_GET['action'];
}
<label class="form-text" id="further-details-labels" for="country">Country:</label>
<select onchange="getCountry(this.value)" class="form-control country" name="country" id="country">
<?php
echo "<option value=\"\">Please select Country</option>";
foreach ($model->getCountry() AS $countries => $country) {
echo "<option value={$country['country_code']}>{$country['country_name']}</option>";
}
?>
</select>
<label class="form-text" id="further-details-labels" for="city">City:</label>
<select class="form-control" name="city" id="further-details-input">
<option value="">Please select City</option>
<?php
switch ($action) {
case "all":
$model = new model();
foreach ($model->getCity() AS $cities => $city) {
echo "<option value={$city['city_code']}>{$city['city_name']}</option>";
}
break;
case 'country':
$country = $_POST['country'];
$model = new model();
foreach ($model->getCityByCountry($country) as $cities => $city) {
echo "<option value={$city['city_code']}>{$city['city_name']}</option>";
}
break;// to continue switch statement and add ajax calls
}
?>
</select>
AJAX
<script type="text/javascript">
// TODO fetching script for onchange
function getCountry(country_code) {
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
} else {
var xhr = new ActiveObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var country = {"country": country_code};
console.log(country);
var test = document.getElementById("test");
// test.innerHTML=this.responseText;
}
};
xhr.open("POST","details.php", true);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send("action=country&country="+country);
};
</script>
Any suggestion as to how to connect them to make the select options change based on the function triggered please?
You need to check $action before printing the rest of the form, not inside the form. If it's all you print the whole form, if it's country you just print the country options.
<?php
switch ($action) {
case "all":
?>
<label class="form-text" id="further-details-labels" for="country">Country:</label>
<select onchange="getCountry(this.value)" class="form-control country" name="country" id="country">
<?php
echo "<option value=\"\">Please select Country</option>";
foreach ($model->getCountry() AS $countries => $country) {
echo "<option value={$country['country_code']}>{$country['country_name']}</option>";
}
?>
</select>
<label class="form-text" id="further-details-labels" for="city">City:</label>
<select class="form-control" name="city" id="further-details-input">
<option value="">Please select City</option>
<?php
$model = new model();
foreach ($model->getCity() AS $cities => $city) {
echo "<option value={$city['city_code']}>{$city['city_name']}</option>";
}
?>
</select>
<?php
break;
case 'country':
$country = $_POST['country'];
$model = new model();
foreach ($model->getCityByCountry($country) as $cities => $city) {
echo "<option value={$city['city_code']}>{$city['city_name']}</option>";
}
break;// to continue switch statement and add ajax calls
}
Then in the AJAX code, the callback function should do:
document.querySelector("select[name=city]").innerHTML = this.responseText;

Dynamic drop down using single table in codeIgniter

Table
Here when I select Category 1 from drop down I should get district names which comes under Category 1 and for Category 2 I should get districts of Category 2 and so on....
As of now in my code i'm pulling out all district names from my district table master by using district codes. But I should get district names based on category selection.
View:
<select class="form-control" name="category" id='cat_id'>
<?php
foreach($query1 as $row)
{
echo '<option value="'.$row->category.'">'.$row->category.'</option>';
}
?>
</select>
<select name="placename" id="placename">
<?php
foreach($query2 as $row)
{
echo '<option value="'.$row->district_name.'">'.$row-
>district_name.'</option>';
}
?>
</select>
Model:
function viewcatplace()
{
$this->db->select("district.district_name");
$this->db->from('district');
$this->db->join('jc_place_master', 'district.district_code =
jc_place_master.district');
$query = $this->db->get();
return $query->result();
}
Controller:
public function viewcatplace()
{
$this->load->model('JcMeetingExpense_model');
$data['query1'] = $this->JcMeetingExpense_model->viewcatprice();
$data['query2'] = $this->JcMeetingExpense_model->viewcatplace();
$this->load->view('JcMeetingExpense/place_view',$data);
}
You can use this demo for your solution : https://www.codexworld.com/dynamic-dependent-dropdown-codeigniter-jquery-ajax/
It can be only done by ajax:
In controller:
public function index()
{
$web = array();
$web['title'] = 'Select tool';
$web['content'] = 'web/category_index';
// $web['data'] = $this->Common_model->get_all('category','*','','');
$web['data'] = $this->db->query('SELECT DISTINCT category FROM category')->result();
$this->load->view('web_template', $web);
}
Load the category data in select option:
<select class="form-control" id="select_category">
<option value="" disabled selected>Select category</option>
<?php if (isset($data) && !empty($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<option value="<?php echo $value->category; ?>"><?php echo $value->category; ?></option>
<?php endforeach; ?>
<?php endif; ?>
</select>
<select class="form-control" id="append_district"></select>
Using jquery change event get the data using ajax call:
<script type="text/javascript">
$(document).on('change',"#select_category",function (e) {
var optVal= $("#select_category option:selected").val();
if (optVal) {
$.ajax({
type: "post",
url: "getCategoryDetails",
cache: false,
data: {'category' : optVal},
success: function(json){
try {
var obj = jQuery.parseJSON(json);
$('#append_district').empty();
var append_data = '';
if (obj.length > 0) {
$.each(obj, function( index, value ) {
append_data += '<option value="'+value.district+'">'+value.district+'</option>'
});
$('#append_district').append(append_data);
}
} catch(e) {
console.log('Exception while request..');
}
},
error: function(){
console.log('Error while request..');
}
});
}
});
</script>
The data can be get by JSON format.In controller add this method:
public function getCategoryDetails() {
$category = $_POST['category'];
$categoryData = $this->db->query('SELECT district FROM category where category="'.$category.'"')->result();
echo json_encode ($categoryData) ;
}

select box using ajax and CakePHP

I'm trying to get data related to parent data from select options , and here's my add.ctp
<select name="id" id="category">
<option value="hide">-- اختر مجموعة الصنف --</option>
<?php foreach ($warehouseCategoriesItems as $warehouseCategoriesItem): ?>
    <option value="<?php echo $warehouseCategoriesItem; ?> " ><?php echo $warehouseCategoriesItem; ?></option>
<?php endforeach; ?>
</select>
<select name="id" id="item">
<option>-- اختر الصنف-- </option>
</select>
and here's the script for that :
<script type="text/javascript">
var types_list = $('#item');
$('#category').change(function(){
carId = $(this).val();
$.ajax({
type: "GET",
url: '../warehouse-add-orders-items-form7/add/' + carId ,
data: { 'carId': carId },
success: function( response ) {
types_list.empty();
types_list.append(
$("<option></option>")
.text('-- إختر نوع --')
.val('')
);
$.each(response, function(id, name) {
types_list.append(
$("<option></option>")
.text(response[id].category_item_name)
.val(response[id].warehouse_categories_items_id)
);
});
types_list.trigger('chosen:updated');
}
});
});
.There's relationship between the category parent and the child items , but i'm getting the child with null values each time and the parent back with it's value .
can any one tell me the problem here ?

Values Are Combining

`I have a script that is returning the right values except for one little problem. Lid is returning 892 which is right, However; Cid which should return 16 its returning 89216 a combination of the two. How can I get Cid to just return 16?
$(document).ready(function()
{
$(".Doggie").change(function()
{
var LocationString ='Lid='+ $(this).val();
$.ajax({
type: "POST",
url: "ajax_city.php",
data: LocationString,
cache: false,
success: function (html) {
$(".Kitty").html(html);
}
});
});
$('.Kitty').live("change",function(){
var Lid = $('#Doggie').val(), // This is the value of the id="Doggie" selected option
Cid = $(this).val(); // This is the value of the id="Kitty" selected option
$.ajax({
type: "POST",
url: "ajax_area.php",
data: {"Lid":Lid,"Cid":Cid},
cache: false,
success: function (html) {
$(".Pig").html(html);
}
});
});
});
</script>
</head>
<body>
<div id="frame1">
<label>Place :</label>
<select name="Doggie" class="Doggie" id="Doggie">
<option selected="selected">--Select Place--</option>
<?php
$sql = mysql_query("SELECT tblLocations.RestID as Lid, tblRestaurants.RestName as name
FROM tblRestaurants INNER JOIN tblLocations ON tblRestaurants.RestID = tblLocations.RestID
GROUP BY tblLocations.RestID, tblRestaurants.RestName
ORDER BY tblRestaurants.RestName ASC");
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['Lid'].'">'.$row['name'].'</option>';
} ?>
</select>
<label>City :</label>
<select name="Kitty" class="Kitty" id="Kitty">
<option selected="selected">--Select City--</option>
</select>
<label>Area: :</label>
<select name="Pig" class="Pig" id="Pig">
<option selected="selected">--Select Area--</option>
</select>
</div>
</body>
</html>
ajax_city.php
<?php
require('config.php');
if($_POST['Lid'])
{
$Lid=$_POST['Lid'];
//$Cid=$_POST['Cid'];
$sql=mysql_query("SELECT tblLocations.RestId as Lid, tblLocations.CityID as Cid, tblCities.CityName as name
FROM tblLocations INNER JOIN tblCities ON tblLocations.CityID = tblCities.CityID
WHERE tblLocations.RestID = $Lid
GROUP BY tblLocations.RestID, tblCities.CityName
ORDER BY tblCities.CityName ASC");
echo '<option selected="selected">--Select City--</option>';
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['Lid'].''.$row['Cid'].'">'.$row['name'].'</option>';
}
}
?>
ajax_area.php
<?php
require('config.php');
if($_POST['Lid'])
{
//$Lid=$_POST['Lid'];
$Cid=$_POST['Cid'];
$sql=mysql_query("SELECT tblLocations.RestId as Lid, tblLocations.CityID as Cid, tblAreas.AreaName as name
FROM tblLocations INNER JOIN tblAreas ON tblLocations.AreaID = tblAreas.AreaID
WHERE tblLocations.RestID = $Lid AND tblLocations.CityID = $Cid
GROUP BY tblLocations.RestID, tblAreas.AreaName
ORDER BY tblAreas.AreaName ASC");
echo '<option selected="selected">--Select Area--</option>';
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['Lid'].''.$row['Cid'].'">'.$row['name'].'</option>';
}
}
?>
It was these two lines in the ajax-city.php file.
"SELECT tblLocations.CityId as Cid, tblCities.CityName as name
And
echo '<option value="'.$row['Cid'].'">'.$row['name'].'</option>';

Categories