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....
}
Related
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
}
?>
i have a simple form in codeigniter website where am trying to display sub categories when categories are selected, i did the following code:
$(document).ready(function() {
$('#country').change(function() {
var country_id = $('#country').val();
if (country_id != '') {
$.ajax({
url: "<?php echo base_url(); ?>index.php/homecontroller/fetchstate",
method: "POST",
data: {
country_id: country_id
},
success: function(data) {
$('#state').html(data);
$('#city').html('<option value="">Select Brand</option>');
}
});
} else {
$('#state').html('<option value="">Select Category</option>');
$('#city').html('<option value="">Select Brand</option>');
}
});
});
<form action="" method="post">
<label for="inputEmail4">Category</label>
<select id="country" class="form-control" name="cname" aria-label="Default select example">
<option>Select Category</option>
<?php
foreach($listcategory as $vals){
echo '<option value="'.$vals->name.'">'.$vals->name.'</option>';
}?>
</select>
<label for="inputEmail4">Brand</label>
<select class="form-control" name="sname" id="state">
<option value="">Select Brand</option>
</select>
i have the controller and model like below:
function fetchstate()
{
if($this->input->post('country_id'))
{
echo $this->excel_import_model->fetch_state($this->input->post('country_id'));
}
}
function fetch_state($country_id)
{
$this->db->where('inventorycategory', $country_id);
$this->db->order_by('name', 'ASC');
$query = $this->db->get('inventorybrand');
$output = '<option value="">Select Brand</option><option value="None">None</option>';
foreach($query->result() as $row)
{
$output .= '<option value="'.$row->name.'">'.$row->name.'</option>';
}
return $output;
}
now here the issue is when i select the category it doesnt display sub category, i get the following error:
POST http://localhost/letsship/index.php/homecontroller/fetchstate 500 (Internal Server Error)
can anyone please tell me what is wrong in here, thanks in advance
I have 2 SelectOption where if Select 1 is selected, then Select 2 automatically synchronizes with Select 1
all SelectOptions contents retrieve from a database table.
SELECT 1 & 2 scripts:
<select name="leavetype" autocomplete="off">
<option value="">Choose Leave Type</option>
<?php $sql = "SELECT LeaveType from tblleavetype";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<option value="<?php echo htmlentities($result->LeaveType);?>"><?php echo htmlentities($result->LeaveType);?></option>
<?php }} ?>
</select>
<select name="rightsgranted" autocomplete="off">
<option value="">Rights Granted</option>
<?php $sql = "SELECT RightsGranted from tblleavetype";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<option value="<?php echo htmlentities($result->RightsGranted);?>"><?php echo htmlentities($result->RightsGranted);?></option>
<?php }} ?>
</select>
example
you need to use ajax for this work
this example is for the select city of a state
index.php
<?php
//Include the database configuration file
include 'dbConfig.php';
//Fetch all the country data
$query = $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
?>
<select id="country">
<option value="">Select Country</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
}
}else{
echo '<option value="">Country not available</option>';
}
?>
</select>
<select id="state">
<option value="">Select country first</option>
</select>
<select id="city">
<option value="">Select state first</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
<select id="state">
<option value="">Select country first</option>
</select>
<select id="city">
<option value="">Select state first</option>
</select>
ajax.php
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
ajaxData.php
<?php
//Include the database configuration file
include 'dbConfig.php';
if(!empty($_POST["country_id"])){
//Fetch all state data
$query = $db->query("SELECT * FROM states WHERE country_id = ".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//State option list
if($rowCount > 0){
echo '<option value="">Select state</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}elseif(!empty($_POST["state_id"])){
//Fetch all city data
$query = $db->query("SELECT * FROM cities WHERE state_id = ".$_POST['state_id']." AND status = 1 ORDER BY city_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//City option list
if($rowCount > 0){
echo '<option value="">Select city</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
see the full tutorial in this link
I Found simple method.
This might not be the best solution, but it should do the trick.
Maybe this will help others: http://jsfiddle.net/7BUmG/3876/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#leavetype').change(function() {
var rightsgranted = $(this).find("option:selected").attr("title");
$('#RightsGranted').val(rightsgranted);
});
});
</script>
<select id="leavetype" name="leavetype" autocomplete="off">
<option value="">Choose Leave Type</option>
<?php $sql = "SELECT LeaveType,RightsGranted from tblleavetype";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<option title="<?php echo htmlentities($result->RightsGranted);?>" value="<?php echo htmlentities($result->LeaveType);?>"><?php echo htmlentities($result->LeaveType);?></option>
<?php }} ?>
</select>
<input type='text' name="RightsGranted" id="RightsGranted" hidden/>
I'm not getting value from a City-list DropDown which is Dynamically made. I'm first making required data Jason using AJAX in a Script and then sending it to another page to create Dynamic DropDown. In this City-list is my dynamic made dropdown which depends on the selection of Provincedown Dropdown but the problem comes when I select any option from City-list dropdown which is Dynamically build using ajax than its very first value comes as a selection no matter what option you have selected. Any Suggestions.Here is my Code of provincedown and City-list Dropdown.
<input type="hidden" name="City_Name" value="<?= $City_Name; ?>" >
<input type="hidden" name="Province_Name" value="<?= $ProvinceName ?>" >
<label>Province: </label><br>
<select name="Provincedown" id="ProvinceDropDown" class="form-control" onChange="getState(this.value);">
<option value="SelectProvince" <?=$ProvinceName == 'SelectProvince' ? ' selected="selected"' : '';?> > Please Select </option>
<option value="Sindh" <?=$ProvinceName == 'Sindh' ? ' selected="selected"' : '';?>> Sindh </option>
</select>
<label>City:</label><br/>
<select name="City-list" id="City-list" >
<option value="SelectCity" >Select City</option>
</select>
making data jason using AJAX whom code is
<body onload="getState()">
<script>
function getState(val) {
//var cityName = $City_Name;
var City_Name = $("input[name='City_Name']").val();
var Province_id = $("input[name='Province_Name']").val();
$.ajax({
type: "POST",
url: "fetch_state_Edit.php",
data:{country_id : val, City_Name : City_Name,Province_id : Province_id},
success: function(data){
$("#City-list").html(data);
}
});
}
</script>
fetch_state_Edit.php
<?php
if(!empty($_POST["Province_id"])) {
$country_id =$_POST['country_id'];
if($country_id=="SelectProvince" || $country_id=="")
$country_id=$_POST['Province_id'];
$City_Name=$_POST['City_Name'];
$results = mysqli_query($con, "SELECT City_Name FROM location WHERE Province = '$country_id' ");
?>
<option value="SelectCity">Select City</option>
<?php
foreach($results as $state) {
?>
<option value="<?php $state["City_Name"]; ?>" <?=$state["City_Name"] == $City_Name ? ' selected="selected"' : '';?>><?php echo $state["City_Name"];</option>
<?php
}
}
?>
Problem is in fetch_state_Edit.php file Just put echo before $state["City_Name"];
<?php
if(!empty($_POST["Province_id"])) {
$country_id =$_POST['country_id'];
if($country_id=="SelectProvince" || $country_id=="")
$country_id=$_POST['Province_id'];
$City_Name=$_POST['City_Name'];
$results = mysqli_query($con, "SELECT City_Name FROM location WHERE Province = '$country_id' ");
?>
<option value="SelectCity">Select City</option>
<?php
foreach($results as $state) {
?>
<option value="<?php echo $state["City_Name"]; ?>" <?=$state["City_Name"] == $City_Name ? ' selected="selected"' : '';?>><?php echo $state["City_Name"]; </option>
<?php
}
}
?>
i have this functioning dependent drop-down, which is used for address, here is my code,
<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>
<select class="form-control" name = 'CT_ID' id = 'CT_ID'>
<option value="">-- Select Type --</option>
</select>
jquery is
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){
var select = $('#CT_ID');
select.html('');
$.each(data, function(i, option){
select.append("<option value='"+option.CT_ID+"'>"+option.CITY+"</option>");
});
}
});
});
});
now what i need is to do another one like this in my form, because i need it for residential and permanent address, i did another one like this
<select class="form-control" name = "PROV_ID2" id = "PROV_ID2">
<option></option>
<?php foreach ($content as $cs) {?>
<option value="<?php echo $cs->PROV_ID; ?>"><?php echo $cs->PROVINCE; ?></option>
<?php } ?>
</select>
<select class="form-control" name = 'CT_ID2' id = 'CT_ID2'>
<option value="">-- Select Type --</option>
</select>
and the jquery is
jQuery(document).ready(function(){
$("#PROV_ID2").change(function() {
var PROVID2 = {"PROVID2" : $('#PROV_ID2').val()};
console.log(PROVID2);
$.ajax({
type: "POST",
data: PROVID2,
url: "<?php base_url(); ?>Employees/dependent_dropdown",
success: function(data){
var select = $('#CT_ID2');
select.html('');
$.each(data, function(i2, option2){
select.append("<option value='"+option2.CT_ID+"'>"+option2.CITY+"</option>");
});
}
});
});
});
im not that sure with the jquery bec. i am not familiar with it, but i need this one finished asap. what is the error? why is the second dependent drop-down not working? thanks
try this for second dropdown, try for first to same thing
<select class="form-control" name = "PROV_ID2" id = "PROV_ID2" onchange="provchange()">
<option></option>
<?php foreach ($content as $cs) {?>
<option value="<?php echo $cs->PROV_ID; ?>"><?php echo $cs->PROVINCE; ?></option>
<?php } ?>
</select>
<select class="form-control" name = 'CT_ID2' id = 'CT_ID2'>
<option value="">-- Select Type --</option>
</select>
jquery js
function provchange(){
var PROV_ID2=$('#PROV_ID2').val();
$.ajax({
url: "<?php echo base_url('Employees/dependent_dropdown/')?>",
type: "post",
data : {
PROV_ID: PROVID2
},
success: function(data){
var json = JSON.parse(data);
//alert(data);
$("#CT_ID2").empty();
$("#CT_ID2").append($('<option></option>').attr('value', '').text(':: SELECT ::'));
ival=0;
for (var i in json) {
$("#CT_ID2").append($('<option></option>').attr('value', json[i].CT_ID).text(json[i].CITY));
}
}
});
}