Jquery help for single select country state fetch data - javascript

here is a code for multiselect which is working fine for multiselect but i need this code to be work in single select , in this Code #Country list is simply getting list from option as you can see in code and when we select #country in dropdown the #state data is fetching from data base according to country selection
( Multi select is Working fine but i need this in Single select )
<script src="js/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<label for="country">Country</label> ( Simple Drop Down for Country )
<?php include "fetch_country.php"; ?>
<select id="country" name="country[]" multiple class="form-control" >
<option value="India" label="India">India</option>
<option value="USA" label="USA">USA</option>
<option value="UK" label="UK">UK</option>
<option value="Canada" label="Canada">Canada</option>
<option value="China" label="China">China</option>
</select>
<div class="col-sm-6">
<label for="state">State</label> ( Fetching State data from Database )
<select id="state" name="state[]" multiple class="form-control" >
<option disabled>Select Country First</option>
</select>
<button class="myButnsbmt" type="submit" name="update" value="Update">Submit</button>
</form>
<script>
$(document).ready(function(){
$('#country').multiselect({
nonSelectedText:'?',
buttonWidth:'250px',
maxHeight: 400,
onChange:function(option, checked){
var selected = this.$select.val();
if(selected.length > 0)
{
$.ajax({
url:"fetch_country.php",
method:"POST",
data:{selected:selected},
success:function(data)
{
$('#state').html(data);
$('#state').multiselect('rebuild');
}
})
}
}
});
$('#state').multiselect({
nonSelectedText: '?',
allSelectedText: 'All',
buttonWidth:'250px',
includeSelectAllOption: true,
maxHeight: 400,
enableFiltering:true
});
});
</script>

Html Part
<div class="container mt-5">
<div class="row">
<div class="card">
<div class="card-header">
<h2 class="text-success">Country State City Dropdown List in PHP MySQL Ajax - Tutsmake.COM</h2>
</div>
<div class="card-body">
<form>
<div class="form-group">
<label for="country">Country</label>
<select class="form-control" id="country-dropdown">
<option value="">Select Country</option>
<?php
require_once "db.php";
$result = mysqli_query($conn, "SELECT * FROM countries");
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="form-group">
<label for="state">State</label>
<select class="form-control" id="state-dropdown">
</select>
</div>
<div class="form-group">
<label for="city">City</label>
<select class="form-control" id="city-dropdown">
</select>
</div>
</form>
</div>
</div>
</div>
</div>
js part
$(document).ready(function () {
$('#country-dropdown').on('change', function () {
var country_id = this.value;
$.ajax({
url: "states-by-country.php",
type: "POST",
data: {
country_id: country_id
},
cache: false,
success: function (result) {
$("#state-dropdown").html(result);
$('#city-dropdown').html('<option value="">Select State First</option>');
}
});
});
$('#state-dropdown').on('change', function () {
var state_id = this.value;
$.ajax({
url: "cities-by-state.php",
type: "POST",
data: {
state_id: state_id
},
cache: false,
success: function (result) {
$("#city-dropdown").html(result);
}
});
});
});
states-by-country.php
<?php
require_once "db.php";
$country_id = $_POST["country_id"];
$result = mysqli_query($conn, "SELECT * FROM states where country_id = $country_id");
?>
<option value="">Select State</option>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option>
<?php
}
?>
cities-by-state.php
<?php
require_once "db.php";
$state_id = $_POST["state_id"];
$result = mysqli_query($conn, "SELECT * FROM cities where state_id = $state_id");
?>
<option value="">Select City</option>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option>
<?php
}
?>

Then try this
<label for="country">Country</label>
<select id="country" name="country" multiple class="form-control">
<option value="India" label="India">India</option>
<option value="USA" label="USA">USA</option>
<option value="UK" label="UK">UK</option>
<option value="Canada" label="Canada">Canada</option>
<option value="China" label="China">China</option>
</select>
<label for="state">State</label> ( Fetching State data from Database )
<select id="state" name="state[]" multiple class="form-control">
<option disabled>Select Country First</option>
</select>
<button class="myButnsbmt" type="submit" name="update" value="Update">Submit</button>
<script>
$(document).ready(function() {
$('#country').on('change', function() {
var countryname = this.value;
$.ajax({
url: "states-by-country.php",
type: "POST",
data: {
country: countryname
},
cache: false,
success: function(result) {
$("#state-dropdown").html(result);
$('#city-dropdown').html('<option value="">Select State First</option>');
}
});
});
});
</script>
states-by-country.php
<?php
require_once "db.php";
$country = $_POST["country"];
$result = mysqli_query($conn, "SELECT * FROM states where countryname = $country");
?>
<option value="">Select State</option>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option>
<?php
}
?>

Related

How to insert dynamic country state city dropdown in php? This code insert only their id

This is js
<script type="text/javascript" src="jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#loding1").hide();
$("#loding2").hide();
$(".state").change(function()
{
$("#loding1").show();
var id=$(this).val();
var dataString = 'id='+ id;
$(".district").find('option').remove();
$(".area").find('option').remove();
$.ajax
({
type: "POST",
url: "get_district.php",
data: dataString,
cache: false,
success: function(html)
{
$("#loding1").hide();
$(".district").html(html);
}
});
});
$(".district").change(function()
{
$("#loding2").show();
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_area.php",
data: dataString,
cache: false,
success: function(html)
{
$("#loding2").hide();
$(".area").html(html);
}
});
});
});
</script>
This is index.php
Here I can select state-district-area dynamically from DB. But when I am inserting this insert only their relative id. But I want to insert state_name,district_name,area_name. Is there any to help me.
<div class="form-control">
<form name="form2" action="" method="post" onSubmit="return valid2();">
<label for="email">State :</label>
<select name="state" class="state">
<option selected="selected">--Select State--</option>
<?php
$stmt = $DB_con->prepare("SELECT * FROM state");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value="<?php echo $row['state_id']; ?>"><?php echo $row['state_name']; ?></option>
<?php
}
?>
</select>
<label>District :</label> <select name="district" class="district">
<option selected="selected">--Select District--</option>
</select>
<img src="ajax-loader.gif" id="loding1"></img>
<label>Area :</label> <select name="area" class="area">
<option selected="selected">--Select Area--</option>
</select>
<img src="ajax-loader.gif" id="loding2"></img>
</div>
</div>
<input type="submit" name="registration" class="btn btn-primary" value="Registration"/>
</form>
</div>
This is get_district.php
<?php
include('dbconfig.php');
if($_POST['id'])
{
$id=$_POST['id'];
$stmt = $DB_con->prepare("SELECT * FROM district_table WHERE state_id=:id");
$stmt->execute(array(':id' => $id));
?><option selected="selected">Select District :</option><?php
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value="<?php echo $row['district_id']; ?>"><?php echo $row['district_name']; ?></option>
<?php
}
}
?>
This is get_area.php
<?php
include('dbconfig.php');
if($_POST['id'])
{
$id=$_POST['id'];
$stmt = $DB_con->prepare("SELECT * FROM area_table WHERE district_id=:id");
$stmt->execute(array(':id' => $id));
?><option selected="selected">Select Area :</option>
<?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value="<?php echo $row['are_id']; ?>"><?php echo $row['area_name']; ?></option>
<?php
}
}
?>
I want to insert state_name,district_name,area_name in DB. But the above code is inserting their id. Please Help me.

ajax dependent dropdown codeigniter

I want to taking id from index using ajax that supply to controller and controller will output category id using json and supply to index file.
Controller
public function index() {
$this->load->model('sales/Sales_model');
$this->load->model('product/Product_model');
$user_info['p_info'] = $this->Product_model->fetch_data();
$this->load->view('sales/index',$user_info);
}
function get_pcatagory(){
$this->load->model('sales/Sales_model');
$pid = $this->input->post('pro_id');
$cat_info = $this->Sales_model->fetch_data_pid($pid);
if(count($cat_info) > 0){
$select_box = '';
$select_box .= 'Select Catagory ID';
foreach ($cat_info as $value) {
// $value->id data will go to option of the select menu
}
echo json_encode($select_box);
}
}
Model
`function fetch_data_pid($pid){
$query = $this->db->get_where('product',array('id'=>$pid));
return $query->result();
}`
Ajax
`
$(document).ready(function(){
$('#pid').on('change',function(){
var pro_id_data = $('#pid').val();
alert(pro_id_data);
$.ajax({
url:'sales/get_pcatagory',
type:'POST',
data:{'pro_id' : pro_id_data},
dataType: 'json',
success:
function(result){
$('#cate').html(result);
},
error:
function(){
alert('error')
}
});
});
});
`
view
<div class="form-group">
<label>Product ID</label>
<select name="p_id" id="pid" class="form-control" placeholder="Enter Product" required>
<option value="0">Select Product ID</option>
<?php
foreach ($p_info as $value) {
?>
<option value="<?php echo $value->id ;?>"><?php echo $value->p_name ;?></option>
<?php }?>
</select>
</div>
<div id="" class="form-group">
<label>Category</label>
<select name="catagory" id="cate" class="form-control" placeholder="Enter Product" required >
</select>
</div>
But it alerts error . How can I solve it ?

Dependent Drop Down select codeigniter Ajax

Im trying to get houses to be filled on the second dropdown from their respective estates selected in the first drop down. Im getting no results in the second dropdown.
This is the HTML:
<div class="col-sm-4 col-xs-12">
<div class="form-group drop-custum">
<select id="estate" name="estate" data-live-search="true" class="form-control show-tick"
onchange="get_houses(this.value)">
<option value="">-- Estate --</option>
<?php
$sql = $this->db->query("select * from estates ORDER BY estate_name asc");
$result = $sql->result();
foreach ($result as $estates):
?>
<option class="text-uppercase"
value="<?= $estates->estate_name?>"> <?= $estates->estate_name?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="col-sm-4 col-xs-12">
<div class="form-group drop-custum">
<select name="house" data-live-search="true" id="house"
class="form-control show-tick">
<option value="">-- House --</option>
</select>
</div>
</div>
This is the AJAX:
function get_houses()
{
$.ajax({
url:"fill_houses/",
type:"POST",
data:'estate_name='+val,
success:function(data)
{
$("#house").html(data);
alert('success');
}
});
}
This is the PHP:
public function fill_houses()
{
$query = "select * from houses where estate_name='" . $_POST["estate_name"] . "' order by house_number asc ";
$result = $query->result();
foreach ($result as $estates):
'<option class="text-uppercase" value="'.$estates->house_id.'"> '.$estates->house_number.'</option>';
endforeach;
}
You must return the value back in php function fill_houses().
public function fill_houses()
{
$query = $this->db->query("select * from houses where estate_name='" . $_POST["estate_name"] . "' order by house_number asc ");
$result = $query->result();
foreach ($result as $estates):
return '<option class="text-uppercase" value="'.$estates->house_id.'"> '.$estates->house_number.'</option>';
endforeach;
}
also in javascript ajax function get_houses() you need to get the variable. and a couple of edit.
function get_houses(val)
{
$.ajax({
url:"fill_houses/",
type:"POST",
data: { 'estate_name': val} ,
success:function(data)
{
$("#house").html(data);
alert('success');
}
});
}

How to cascade three dropdown using PHP and JS?

I have a custom page template with three dropdown, the values of each dropdown is populate dynamically. Now, I want to cascade it. Whatever option the user choose in 1st dropdown, the values that under of that option will be displayed as an options in 2nd dropdown, same as in the 3rd dropdown.
I have a JS snippet, but the cascading of the three dropdown is not working
Snippet PHP:
<form action='' method='post' name='test' id='test'>
<div class="div-select">
<label for="list_position" id="idname">Position</label>
<br/>
<select name="list_position" id="filterbypostion" onchange="app_position(this.form)">
<option name="default" class="filter_by" selected="selected" value="Select by Position">Select by Position</option>
<?php
foreach($query_location as $option){
if(isset($_POST['list_position']) && $_POST['list_position'] == $option->position)
echo '<option name="list_position" class="filter_by" selected value="'.$option->position.'">'.$option->position.'</option>';
else
echo '<option name="list_position" class="filter_by" value="'.$option->position.'">'.$option->position.'</option>';
};
?>
</select>
</div>
<div class="div-select">
<label for="list_position" id="idname">Position</label>
<br/>
<select name="list_position" id="filterbypostion" onchange="app_location(this.form)">
<option name="default" class="filter_by" selected="selected" value="Select by Position">Select by Position</option>
<?php
foreach($query_location as $option){
if(isset($_POST['list_position']) && $_POST['list_position'] == $option->position)
echo '<option name="list_position" class="filter_by" selected value="'.$option->position.'">'.$option->position.'</option>';
else
echo '<option name="list_position" class="filter_by" value="'.$option->position.'">'.$option->position.'</option>';
};
?>
</select>
</div>
<div class="div-select">
<label for="list_position" id="idname">Position</label>
<br/>
<select name="list_position" id="filterbypostion" onchange="app_location(this.form)">
<option name="default" class="filter_by" selected="selected" value="Select by Position">Select by Position</option>
<?php
foreach($query_location as $option){
if(isset($_POST['list_position']) && $_POST['list_position'] == $option->position)
echo '<option name="list_position" class="filter_by" selected value="'.$option->position.'">'.$option->position.'</option>';
else
echo '<option name="list_position" class="filter_by" value="'.$option->position.'">'.$option->position.'</option>';
};
?>
</select>
</div>
<div class="div-input">
<input type="submit" value="Search" class="div-input-submit"/>
</div>
</form>
Snippet JS:
function app_position(form){
var val=form.list_position.options[form.list_position.options.selectedIndex].value;
self.location='page-resume-databank?list_position=' + val ;
}
function app_location(form){
var val=form.list_position.options[form.list_position.options.selectedIndex].value;
var val2=form.list_location.options[form.list_location.options.selectedIndex].value;
self.location='page-namepage?list_location=' + val + '&list_processed=' + val2 ;
}
<form action='' method='post' name='resumeDatabank' id='resumeDatabank'>
<div class="div-select">
<label for="list_position" id="#ddress_search LABEL">Position</label>
<br/>
<select name="list_position" id="filterbypostion" onchange="app_position(this.value)">
<option name="default" class="filter_by" selected="selected" value="Select by Position">Select by Position</option>
<?php
foreach($query_location as $option){
if(isset($_POST['list_position']) && $_POST['list_position'] == $option->position)
echo '<option name="list_position" class="filter_by" selected value="'.$option->position.'">'.$option->position.'</option>';
else
echo '<option name="list_position" class="filter_by" value="'.$option->position.'">'.$option->position.'</option>';
};
?>
</select>
</div>
<div class="div-select" id="show_street">
<label for="list_position" id="#address_search LABEL">Street</label>
<br/>
<select name="list_position" id="filterbypostion">
<option name="default" class="filter_by" selected="selected" value="Select by Position">Select Road</option>
</select>
</div>
<div class="div-select" id="show_roads">
<label for="list_position" id="#address_search LABEL">Roads</label>
<br/>
<select name="list_position" id="filterbypostion">
<option name="default" class="filter_by" selected="selected" value="Select by Position">Select Road</option>
</select>
</div>
<div class="div-input">
<input type="submit" value="Search" class="div-input-submit"/>
</div>
</form>
<script>
function app_position(city){
//city is selected value of city drop down
//give the correct path to you ajax.php
$.ajax({
type: "POST",
url: 'ajax.php',
data: "city="+city+"type=street" ,
success: function(data)
{
$("#show_street").html(data);
}
});
}
function app_location(street){
//street is selected value of street drop down
//give the correct path to you ajax.php
$.ajax({
type: "POST",
url: 'ajax.php',
data: "street="+street+"type=roads" ,
success: function(data)
{
$("#show_roads").html(data);
}
});
}
</script>
in you ajax.php file
<?php
$type = $_POST['type'];//this type will load the relevant function.
if($type="street"){
$city = $_POST['city'];
//now get the value of streets belongs to this city
$your_query = "Select * from street_table where city_id=$city";//you can modify this query according to your table
$res = mysql_query($your_query);
?>
<label for="list_position" id="#address_search LABEL">Street</label>
<br/>
<select name="list_position" id="filterbypostion" onchange="app_location(this.value)">
<?php while($raws = mysql_fetch_assoc($res)){?>
<option name="default" class="filter_by" selected="selected" value="<?php echo $raws['street_id']?>"><?php echo $raws['street_name']?></option>
<?php }//END OF WHILE?>
</select>
<?php }//END OF IF CHECcing street option
if($type="roads"){
$street = $_POST['street'];
//now get the value of streets belongs to this city
$your_query_roads = "Select * from road_table where street_id=$street";////you can modify this query according to your table
$res_roads = mysql_query($your_query_roads);
?>
<label for="list_position" id="#address_search LABEL">Street</label>
<br/>
<?php while($raws_roads = mysql_fetch_assoc($res_roads)){?>
<input name="roads" type="radio" value="<?php echo $raws_roads['road_id'];?>">
<?php }//END OF WHILE?>
<?php
}
?>
You can do it in another way, the other two select box can be fetch from ajax request by posting which box you want , and the entire select box you can send from a component,
like :
$("#country").live("change", function(){
$.post("component.php", country:$(this).val(), function(data){
$("#state-div").html(data);
}
});
and same for other two.

Two dropdown with one onchange

Hi what I'm trying to do is I have 2 dropdown. I want that the ajax will only work if the two dropdown has value selected. And how do I pass the datas of the two?
Here is my code right now
SCRIPT
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
$("#state-list").val(data);
}
});
}
</script>
INDEX
<label>Group:</label><br/>
<select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Group</option>
<?php
while($row = mysql_fetch_array($results)) {
?>
<option value="<?php echo $row["g_id"]; ?>"><?php echo $row["g_name"]; ?> </option>
<?php
}
?>
</select>
<label>Division:</label><br/>
<select name="division" id="div-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Division</option>
<?php
while($row = mysql_fetch_array($results2)) {
?>
<option value="<?php echo $row["d_id"]; ?>"><?php echo $row["div_name"]; ?> </option>
<?php
}
?>
</select>
getstate.php
<?php
include("dbcon2.php");
if(!empty($_POST["country_id"])) {
$query ="SELECT * FROM personnel_gdd WHERE pg_group = '" . $_POST["country_id"] . "' ";
$results = mysql_query($query) or die(mysql_error());
?>
<?php
$row = mysql_num_rows($results)
?>
<?php echo $row; ?>
PS: I know that mysql is deprecated. I'll change it as soon as this problem is fixed. Thanks!
change
onchange="getState()"
donot pass any value in onchange event. And change your script like this
<script>
function getState(val) {
var country = $("#country-list").val();
var div = $("#div-list").val();
if(country && div) {
$.ajax({
type: "POST",
url: "get_state.php",
data:{"country_id": country,"div":div},
success: function(data){
$("#state-list").val(data);
}
});
}
}
</script>
This answer is generic, not related to your data but you will can understand how to figure it out.
$('select').change(function() {
var group = $('#country-list').val();
var div = $('#div-list').val();
if (group == -1 || div == -1) {
alert('please select country and division');
}
else {
$.ajax({
type: "POST",
url: "get_state.php",
data:'country_id=' + country + '&=div_id' + div,
success: function(data){
$("#state-list").val(data);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<label>Group:</label>
<select name="country" id="country-list" class="demoInputBox">
<option value="-1">Select Group</option>
<option value="1">Country 1</option>
<option value="1">Country 1</option>
<option value="2">Country 2</option>
<option value="3">Country 3</option>
</select>
<br />
<label>Division:</label>
<select name="division" id="div-list" class="demoInputBox">
<option value="-1">Select Division</option>
<option value="1">Division 1</option>
<option value="2">Division 2</option>
<option value="3">Division 3</option>
</select>
Than you get the 2 values in the server and return the data to the client. Than put this data into the third dropdown.
HTML
<label>Country:</label><br/>
<select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Country</option>
<?php
$selq = "your query..............";
$selm = mysql_query($selq);
while($row = mysql_fetch_array($selm))
{
?>
<option value="<?php echo $row["country_id"]; ?>"><?php echo $row["name"]; ?> </option>
<?php
}
?>
</select>
<select name="state" id="state-list" >
</select>
Javascript function
function getState(val) {
$.ajax({
type: "POST",
url: "test2.php",
data:'country_id='+val,
success: function(data){
$("#state-list").append('<option value=""></option>');
$('#state-list').html(data);
}
});
}
Ajax PHP file
if(!empty($_POST["country_id"]))
{
$query ="your query............... ";
$results = mysql_query($query) or die(mysql_error());
while($fetch = mysql_fetch_array($results))
{
?>
<option value="<?php echo $fetch['id']?>" ><?php echo $fetch['name'] ?></option>
<?php
}
}
You only need to check if all values are different from -1 or "" or whatever - then build the data object and fire the Ajax:
JSnippet Demo
function runAjax() {
//Check both:
check = true;
$('select').each(function(){
console.log($(this).val())
if ($(this).val() == -1) {
$('span').text("Please select both.");
check = false
}
});
if (!check) return;
$('span').text("OK. submiting");
//Get the data:
var data = {
select1: $('#sel1').val(),
select2: $('#sel2').val()
};
//Go on with ajax....
}

Categories

Resources