I am trying to pass a value of a select option input using Ajax into another page PHP and get the database and fetch data into select option. However, my problem is there is nothing to show in second select option.
I have the select option called Country which contains Country 1, Country 2, Country 3, Country 4 with cid 1,2,3,4.
what I wanted is past Country ID (cid) into getdata.php and query the database of City which contains City a, city b, city c, etc. and fetch city's data into select option using Ajax.
I need to make city select option dynamically change when I select the country.
here is my database structure :
Country.db
City.db
Here is my script :
dropdown.php
<?php
require_once "connection.php";
?>
<html>
<head>
<title>Dropdown ajax</title>
</head>
<body>
<div class="country" >
<label>Country</label>
<select name="country" onchange="getId(this.value);">
<option value=""> -- Select Country -- </option>
<!-- populate value using php -->
<?php
$query = "SELECT * FROM country";
$result = mysqli_query($con,$query);
//loop
foreach ($result as $country) {
?>
<option value="<?php echo $country["cid"]; ?>"> <?php echo $country["country"]; ?> </option>
<?php
}
?>
</select>
</div>
<div class="city">
<label>City</label>
<select name="city" id="cityList">
<option value=""></option>
</select>
</div>
<script src="jquery-3.2.1.min"></script>
<script type="text/javascript">
function getId(val){
// ajax function
$.ajax({
type:"POST",
url:"getdata.php",
data:"cid="+val,
success:function(data){
$(#cityList).html(data);
}
});
}
</script>
</body>
</html>
from the dropdown, I am trying to past cid into getdata.php using ajax and fetch the database into select option inside drop-down.php
getdata.php
<?php
require_once "connection.php";
if(!empty($_POST["cid"])){
$cid = $_POST["cid"];
$query = "SELECT * FROM city WHERE cid = $cid";
$result = mysqli_query($con,$query);
foreach ($result as $city) {
?>
<option value="<?php echo $city["cityId"];?>"><?php echo $city["city"];?></option>
<?php
}
}
?>
here is my connection.php
<?php
$con = mysqli_connect("localhost","root","admin","dropdowndb");
//check connection
if(mysqli_connect_errno()){
echo "Failed to connect :".mysqli_connect_errno();
}
?>
the result is like this :
so how to fix this problem?
The selector inside the ajax success handler must be a string, not identifier:
success:function(data){
$('#cityList').html(data);
}
Related
I am having significant issues trying to get the AJAX to fire on this PHP code.
I can get the first field populated without issue, however the AJAX call does not seem to populate the first dependency (and therefore the second). I am an AJAX newbie (and have googled extensively) but cannot seem to crack this one.
Note that the ladb.php file runs fine.
<?php
// Include the database config file
include_once 'ladb.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body style="background: #D5DDE0">
<div class="container">
<form action="" method="post">
<div class="form-group col-md-6">
<!-- Country dropdown -->
<label for="country">Country</label>
<select class="form-control" id="country">
<option value="">Select Country</option>
<?php
$query = "SELECT * FROM City_Index GROUP BY country ORDER BY country ASC";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<option value='{$row["countryid"]}'>{$row['country']}</option>";
}
}else{
echo "<option value=''>Country not available</option>";
}
?>
</select><br>
<!-- State dropdown -->
<label for="admin">Administrative Area</label>
<select class="form-control" id="admin">
<option value="">Select Administrative Area</option>
</select><br>
<!-- City dropdown -->
<label for="city">city_ascii</label>
<select class="form-control" id="city">
<option value="">Select City</option>
</select>
</div>
</form>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
// Country dependent ajax
$("#country").on("change",function(){
var country = $(this).val();
if (countryid) {
$.ajax({
url :"action.php",
type:"POST",
cache:false,
data:{countryid:countryid},
success:function(data){
$("#admin").html(data);
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
}else{
$('#admin').html('<option value="">Select Country</option>');
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
// state dependent ajax
$("#admin").on("change", function(){
var admin = $(this).val();
if (admin) {
$.ajax({
url :"action.php",
type:"POST",
cache:false,
data:{admin:admin},
success:function(data){
$("#city").html(data);
}
});
}else{
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
});
</script>
The action.php file below
<?php
// Include the database config file
include_once 'ladb.php';
// Get country id through state name
$country = $_POST['country'];
if (!empty($country)) {
// Fetch state name base on country id
$query = "SELECT * FROM CityList WHERE country = {$country} GROUP BY admin_name_ascii";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['admin_id'].'">'.$row['admin_name_ascii'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}elseif (!empty($_POST['admin'])) {
$admin = $_POST['admin'];
// Fetch city name base on state id
$query = "SELECT * FROM CityList WHERE admin_id = {$admin}";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['cityid'].'">'.$row['city_ascii'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
Any help greatly appreciated!
Thanks to #zergski I note that one of references were defined (countryid in Line 53). DevTools is my new best friend.
I have created a dropdown that populates another dropdown.
I have created a modal for update in my application and I want the selected value of the dropdown to be the name taken from the database. It shows the name, but the problem is it doesnt show the other names which should be included.
(Note that the names show up depending on the first dropdown)
Here is my Model
function get_agents($campaign_id)
{
$campaign_id1 = mysqli_real_escape_string($this->db->conn_id,trim($campaign_id));
$query = $this->db->query("SELECT tbl_employee.emp_id, CONCAT(tbl_applicant.fname, ' ', tbl_applicant.lname) AS fullname FROM tbl_applicant INNER JOIN tbl_employee ON tbl_employee.apid=tbl_applicant.apid INNER JOIN tbl_account ON tbl_employee.acc_id=tbl_account.acc_id WHERE tbl_account.acc_id='".$campaign_id1."' ORDER BY tbl_applicant.fname ASC");
return $query->result();
}
Here is my Controller
public function getAgents()
{
$campaign_id = $this->input->post('campaign_id');
$data = $this->KudosModel->get_agents($campaign_id);
echo "<option value=''>-- Select Ambassador Name --</option>";
foreach($data as $a)
{
echo "<option value='".$a->emp_id."'>".$a->fullname."</option>";
}
}
Here is my View
<div class="form-group" style="height: auto; overflow: auto;">
<label class="col-sm-3 control-label float-left">Ambassador Name</label>
<div class="col-sm-9">
<select class="form-control" id="agentNames<?php echo $val->kudos_id; ?>" required="true" data-trigger="change" value="<?php echo $val->ambassador; ?>">
<option selected="" value="">-- Select Ambassador Name --</option>
<option selected="selected" value=""><?php echo $val->ambassador;?></option>
<?php
foreach($name2 as $row)
{
if($val->campaign==$row->acc_name)
echo '<'; if($val->ambassador==$row->fullname){
echo 'selected=selected';
}echo'option value="'.$row->emp_id.'">'.$row->fullname.'</option>';
}
?>
</select>
</div>
Here is my JQuery
$('#addCampaign<?php echo $val->kudos_id; ?>').on('change', function(){
$.ajax({
type : 'POST',
data : 'campaign_id='+ $('#addCampaign<?php echo $val->kudos_id; ?>').val(),
url : "<?php echo base_url(); ?>index.php/Kudos/getAgents/",
success : function(data){
//data returns your name, iterate through it and add the name to another select
$('#agentNames<?php echo $val->kudos_id; ?>').html(data);
}
});
});
I am using magento 2.1.0. I created two dropdown on customer registration form ,where the data is fetching from database.
There are two databases :
city database which contain city_id and city column.
send is area table which contain area_id, city_id and area column.
on frontend data is sucessfully fetch, and even onchange is also working on city.
City dropdown:
<select name="city" onchange="getArea()" id="city">
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$model = $objectManager->create('/city')->serviceCity();
foreach ($model as $d)
{ ?>
<option id="<?php echo $d['city_id']; ?>" value="<?php echo $d['city_id']; ?>"><?php echo $d['city']; ?></option>
<?php } ?>
</select>
Area dropdown:
<div class="field area required">
<label for="area" class="label"><span><?php /* #escapeNotVerified */
echo __('Area') ?></span></label>
<select name="area" id="area">
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$model = $objectManager->create('\Area')->serviceArea();
foreach ($model as $a)
{ ?>
<option value="<?php echo $a['area']; ?>"><?php echo $a['area']; ?></option>
<?php } ?>
</select>
</div>
Onchange script:
<script>
function getArea(){
alert(document.getElementById('city').value);
}
</script>
Now my question is, what should I do, when I change the city, in second dropdown related area will display only?
Thanks in advance
Few days I try to solve problem but no luck.
Problem is next:
Web form with dependent dropdown select box where user can select his
city, zip and street and that work but.
When I submit form in my database no city_name (text) - only city_id (number/value).
So, question is - How to post city_name in database? User is from Rome and I Rome (text) is submited not city_id (number).
Select input:
<div class="form-group">
<label class="col-md-4 control-label" for="grad">City:*</label>
<div class="col-md-4">
<select type="text" name="city_name" id="city_name" class="form-control input-sm">
<option value=""></option>
<option value="999">---Enter city yourself---</option>
<?php $sql_query="SELECT * FROM city_table order by city_id asc";
$result=mysqli_query($dbconfig,$sql_query);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
?>
<option value="<?php echo $row['city_id'].'_'.$row['city_name'];?>"><?php echo $row['city_name'];?></option>
<?php }?>
</select>
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="post_no">ZIP code:*</label>
<div class="col-md-4">
<select name="zip_name" id="zip_name" class="form-control input-sm" onchange="recalculate_price();">
</select>
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="address">Street:*</label>
<div class="col-md-4">
<select name="street_name" id="street_name" class="form-control input-sm" onchange="recalculate_price();">
</select>
</div>
</div>
get_zip_php
<?php
include('db_config.php');
if($_POST['id'])
{
$id=$_POST['id'];
$sql_query="SELECT * FROM zip_table where city_id='$id' order by zip_name asc";
$result=mysqli_query($dbconfig,$sql_query);
?>
<option selected="selected">Select ZIP code :</option><?php
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
?>
<option value="<?php echo $row['zip_id']; ?>-<?php echo $row['limousine']; ?>-<?php echo $row['kombi']; ?>-<?php echo $row['mini_van']; ?>"><?php echo $row['zip_name']; ?></option>
<?php
}
}
?>
get_street_php
<?php
include('db_config.php');
if($_POST['id'])
{
$id=$_POST['id'];
$sql_query="SELECT * FROM street_table where zip_id='$id' order by street_name asc";
$result=mysqli_query($dbconfig,$sql_query);
?>
<option selected="selected">Select street please :</option><?php
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
?>
<option value="<?php echo $row['street_id']; ?>"><?php echo $row['street_name']; ?></option>
<?php
}
}
?>
Ajax:
<script>
$(document).ready(function()
{
$("#city_name").change(function()
{
var id=$(this).val();
var data = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_zip.php",
data: data,
cache: false,
success: function(html)
{
$("#zip_name").html(html);
recalculate_price();
}
});
});
$("#zip_name").change(function()
{
var id=$(this).val();
var data = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_street.php",
data: data,
cache: false,
success: function(html)
{
$("#street_name").html(html);
recalculate_price();
}
});
});
});
</script>
If I make some changes on "select city part" (Im beginner and really Im lost in all this) I can`t pass zip.
So, please tell me where to make all changes to pass all that things and post city_name, zip (name...I make it as "xxxx - city") and street name. Please help me, I googled and read here about problems few days and can`t continue work on my project until I fix this. Thanks in advance.
Use bellow select tag. It may useful for you
<select type="text" name="city_name" id="city_name" class="form-control input-sm">
<option value=""></option>
<option value="999">---Enter city yourself---</option>
<?php
$sql_query="SELECT * FROM city_table order by city_id asc";
$result=mysqli_query($dbconfig,$sql_query);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<option value='".$row['city_id']."'>".$row['city_name']."</option>";
}
?>
</select>
Concatenate the id with value like this using delimiter like this
<option value="<?php echo $row['city_id'].'_'.$row['city_name'];?>"><?php echo $row['city_name'];?></option>
In php use explode()
The explode() function breaks a string into an array.
$ss = explode('_','6_Rome');
print_r($ss);
echo $ss[0]; //6 pass the value into query
In jquery use split()
Split a string into an array of substrings:
use split()
$vv = variable_name.split("_");
fetch city name from database on the basis of city id in your POST array before INSERT Query.
SELECT `city_name` FROM `city_table` WHERE `city_id`='".$_POST['city_name']."'
then use that city name in your insert query.
I am populating a combo box from database, the problem is when I select an item from the combo box and try to save to another table in the database it picks the record ID column instead of the item itself.
this is the how am populating the combo box.
<label>State</label>
<select name="state" class="state" onChange="display(this.value)" width="142" style="width: 142px">
<option value="" selected="selected">-- Select State --</option>
<?php
$query="select * from tbl_state";
$query_result=mysql_query($query)or mysql_error();
while($row=mysql_fetch_array($query_result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['state_name']; ?></option>
<?php
}
?>
</select>
<div id="show_city" style="position: relative" height:5px;>
<label>LGA</label>
<select name="city" class="lga" width="142" style="width: 142px">
<option value="" selected="selected">-- Select LGA --</option>
</select>
</div>
</p>
Database connection
$state = $_POST['state'];
$city = $_POST['city'];
$sql="INSERT INTO members (state, city)
VALUES ('$state', '$city')";
NB. am using javascript to populate the combo box.
When you submit a form, only the field name along with its value will be sent. In your case, when the user select the state and press submit, the row id will be sent as you specify the row id at the option value tag.
Either you can use <option value="<?= $row['state_name'] ?>"> ... </option>" and then get the state name ini php directly:
$state = $_POST['state'];
or leave the populating code as is now and get the state name by querying database using the record id.
$state_id = intval($_POST['state']);
$city_id = intval($_POST['city']);
$sql = "SELECT `state_name` FROM tbl_state WHERE id=$state_id";
$query_result = mysql_query($sql) or mysql_error();
$state = mysql_result($query_result, 0);
echo $state;
getcity.php
<?php
$con=mysql_connect('localhost','root','') or die('Mysql not connected');
mysql_select_db('thriftdb',$con) or die('DataBase not connected');
$state_id=$_REQUEST['state_id'];
$query="select * from lga where state_id='$state_id'";
?>
<label>LGA</label>
<select name="city" width="142" style="width: 142px">
<option value="" selected="selected">-- Select LGA --</option>
<?php
$query_result=mysql_query($query)or mysql_error();
while($row=mysql_fetch_array($query_result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['lga_name']; ?></option>
<?php
}
?>
</select>
database structure is as follows
'lga' table has...
lga_id --- state_id --- lga_name
'state' table has
state_id --- state_name
When a form sends the selected item of a combo, it sends the value of the option selected, not the text. If you want to send the text, add a hidden input for every combo, then in the onclick event of the combos, call a function that populates the text to the hidden input.
selectState = function() {
$('#hiddenInputField').val($("select[name='state'] option:selected").text());
}
Then in the server side you must get the value of the input hidden field instead of the select field.