I am fairly new to programming so if you can include explanations so I can learn as I go will be very appreciated.
Ok So I am making a drop down menu from sql tables and I am using php and Jquery. So far I have gotten my first sub menu which is states to populate from my country menu. Now I am getting confused on how to get my city menu to populate from my state menu.
Here is my main php file!
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#flip").click(function() {
jQuery("#panel").slideToggle("slow");
});
jQuery("#country").change(function() {
//jQuery("#address").val(jQuery("#courseid :selected").val());
var querystr = 'countryid='+jQuery('#country :selected').val();
jQuery.post("<?php echo plugins_url(); ?>/CountryStateCity Drop Down/ajax.php", querystr, function(data){
if(data.errorcode == 0){
jQuery('#statecbo').html(data.chtml)
//jQuery('#citydescr').append('<textarea name="citydescr" id="citydescr" cols="80" rows="3" maxlength="500"></textarea>')
}else{
jQuery('#statecbo').html(data.chtml)
}
}, "json");
});
});
</script>
<html>
<head>
<title>Dynamic Drop Down Menu</title>
</head>
<body>
<div class="wrap">
<h5> Country</h5>
<select id="country" name="country" required>
<option value="">--Select Country--</option>
<?php
$sql=mysql_query("SELECT * from country order by name");
while ($row=mysql_fetch_array($sql)) {
$countryID=$row['IDCountry'];
$countryname=$row['name'];
echo "<option value='$countryID'>$countryname</option>";
}
?>
</select>
</div>
<h5>State</h5>
<div class="wrap" id="statecbo">
</div>
<div class="wrap">
<h5>City</h5>
</div>
</body>
</html>
And here is my ajax.php file
$country_id = isset($_POST['countryid']) ? $_POST['countryid'] : 0;
if ($country_id <> 0) {
$errorcode = 0;
$strmsg = "";
$sql="SELECT * from state WHERE IDCountry = ". $country_id . " ORDER BY name;";
$result=mysql_query($sql);
$cont=mysql_num_rows($result);
if(mysql_num_rows($result)){
$chtml = '<select name="states" id="states"><option value="0">--Select State-- </option>';
while($row = mysql_fetch_array($result)){
$chtml .= '<option value="'.$row['IDState'].'">'.$row['name'].'</option>';
}
$chtml .= '</select>';
echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$chtml));
}else{
$errorcode = 1;
$strmsg = '<font style="color:#F00;">No States available</font>';
echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$strmsg));
}
}
So my next step would be to add a city menu that is populated by the state menu I just populated from the country menu. Sorry if that is confusing. Thanks!
Based of off jeroen response here is what I added to try and get the city drop down menu.
My main php file--
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#flip").click(function() {
jQuery("#panel").slideToggle("slow");
});
jQuery("#country").change(function() {
var querystr = 'countryid='+jQuery('#country :selected').val();
jQuery.post("<?php echo plugins_url(); ?>/CountryStateCity Drop Down/ajax.php", querystr, function(data){
if(data.errorcode == 0){
jQuery('#statecbo').html(data.chtml)
}else{
jQuery('#statecbo').html(data.chtml)
}
}, "json");
});
jquery(".wrap").on('change', '#states',function() {
var querystr = 'stateid=' +jQuery('#states :selected').val();
jquery.post("<?php echo plugins_url(); ?>/CountryStateCity Drop Down/ajax.php", querystr, function(data) {
if(data.errorcode ==0){
jQuery('#citycbo').html(data.chtml)
}else{
jQuery('#citycbo').html(data.chtml)
}
}, "json");
});
});
</script>
and my ajax.php file
$country_id = isset($_POST['countryid']) ? $_POST['countryid'] : 0;
if ($country_id <> 0) {
$errorcode = 0;
$strmsg = "";
$sql="SELECT * from state WHERE IDCountry = ". $country_id . " ORDER BY name;";
$result=mysql_query($sql);
$cont=mysql_num_rows($result);
if(mysql_num_rows($result)){
$chtml = '<select name="states" id="states"><option value="0">--Select State--</option>';
while($row = mysql_fetch_array($result)){
$chtml .= '<option value="'.$row['IDState'].'">'.$row['name'].'</option>';
}
$chtml .= '</select>';
echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$chtml));
}else{
$errorcode = 1;
$strmsg = '<font style="color:#F00;">No States available</font>';
echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$strmsg));
}
}
$state_id = isset($_POST['IDState']) ? $_POST['IDState'] : 0;
if ($state_id <> 0) {
$errorcode = 0;
$strmsg = "";
$sql="SELECT * from state WHERE IDState = ". $state_id . " ORDER BY name;";
$result=mysql_query($sql);
$cont=mysql_num_rows($result);
if(mysql_num_rows($result)){
$chtml = '<select name="city" id="city"><option value="0">--Select city-- </option>';
while($row = mysql_fetch_array($result)){
$chtml .= '<option value="'.$row['IDCity'].'">'.$row['name'].'</option>';
}
$chtml .= '</select>';
echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$chtml));
}else{
$errorcode = 1;
$strmsg = '<font style="color:#F00;">No city available</font>';
echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$strmsg));
}
}
You basically do the same thing you have done with the country / states.
However, you are using the jQuery change() function so that will not work with elements that were not on the page when that function was registered.
You can solve that by using event delegation:
jQuery(".wrap").on('change', '#states', function() {
// do your stuff
}
I have used the .wrap element as that is the one that wraps your form elements, but you could also use document for example.
And you can of course use the same method for what you have already, just change:
jQuery("#country").change(function() {
to:
jQuery(".wrap").on('change', '#country', function() {
Related
I created 2 dropdown lists where the second one is populated from database based on the option selected in the first one using Ajax.
It's working fine but I want to change the call in my ajax from url:"get-City.php" to the same page instead of creating get-city.php I want to put all the code in one page.
Here is my index.php
<?php
include('connection.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="">
<label>Country :</label>
<select name="country" id="country">
<option value=''>------- Select --------</option>
<?php
$query = 'SELECT DISTINCT Country FROM ****';
foreach ($dbDB->query($query) as $row) {
echo '<option value="'.$row["Country"].'">'.$row["Country"].'</option>';
}
?>
</select>
<label>City :</label>
<select name="city" id="city"><option>------- Select --------</option></select>
</div>
</body>
</html>
<script>
$(document).ready(function() {
$("#country").change(function() {
var country_name = $(this).val();
if(country_name != "") {
$.ajax({
url:"get-City.php",
data:{selected_country:country_name},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#city").html(resp);
}
});
} else {
$("#city").html("<option value=''>------- Select --------</option>");
}
});
});
</script>
and City.php
<?php
include('connection.php');
if(isset($_POST['selected_country'])) {
$sql = "SELECT DISTINCT City FROM **** WHERE Country = '".$_POST['selected_country']."'ORDER BY City";
$res = $dbDB->prepare($sql);
$res->execute();
$count = count($res->fetchAll());
if($count > 0) {
echo "<option value=''>------- Select --------</option>";
foreach ($dbDB->query($sql) as $row) {
echo '<option value="'.$row["City"].'">'.$row["City"].'</option>'; }
} }
else { header('location: ./'); }
?>
Now I wanted to merge both files on the same page and make the AJAX call on the same page. Here is my updated file
<?php
include('connection.php');
if(isset($_POST['selected_country'])) {
$sql = "SELECT DISTINCT City FROM **** WHERE Country = '".$_POST['selected_country']."'ORDER BY City";
$res = $dbDB->prepare($sql);
$res->execute();
$count = count($res->fetchAll());
if($count > 0) {
echo "<option value=''>------- Select --------</option>";
foreach ($dbDB->query($sql) as $row) {
echo '<option value="'.$row["City"].'">'.$row["City"].'</option>'; }
} }
else { header('location: ./'); }
?>
<!DOCTYPE html>
<html>
<head>
<title>demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="">
<label>Country :</label>
<select name="country" id="country">
<option value=''>------- Select --------</option>
<?php
include('connection.php');
$query = 'SELECT DISTINCT Country FROM **** ORDER BY Country ASC';
foreach ($dbDB->query($query) as $row) {
echo '<option value="'.$row["Country"].'">'.$row["Country"].'</option>';
}
?>
</select>
<label>City :</label>
<select name="city" id="city"><option>------- Select --------</option></select>
</div>
</body>
</html>
<script>
$(document).ready(function() {
$("#country").change(function() {
var country_name = $(this).val();
if(country_name != "") {
$.ajax({
data:{selected_country:country_name},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#city").html(resp);
}
});
} else {
$("#city").html("<option value=''>------- Select --------</option>");
}
});
});
</script>
Everytime I select a country then second dropdown list is empty. Can you please advise me what I am missing ? Thank you.
I have created 2 drop down menus where the second one should be reacting to the selection of the first.
I have tested both MySQL querys and the work without any problem. For some reason it seems that page getter.php is not 'activated'. Any suggestions?
mainpage
<?php
require_once('includes/db_connect.php');
echo '<select id="first-choice">
<option>Please choose here first</option>';
$sql_lev = "SELECT
id,
klantnaam
FROM adressen
ORDER BY klantnaam ASC ";
if(!$res_lev = mysqli_query($mysqli, $sql_lev)) { include('includes/error_database.php'); die; }
while($row_lev = mysqli_fetch_array($res_lev)) {
echo '<option value="'.$row_lev['id'].'">'.$row_lev['klantnaam'].'</option>';
}
echo '
</select>
<br>
<select id="second-choice">
<option>Please choose from above</option>
</select>';
?>
<script type="text/javascript">
$("#first-choice").change(function() {
$("#second-choice").load("getter.php?choice=" + $("#first-choice").val());
});
</script>
getter.php
<?php
require_once('includes/db_connect.php');
$choice = mysqli_real_escape_string($mysqli, $_GET['choice']);
echo '<option value="">Choose here now</option>';
$sql_cnt = "SELECT
id,
naam
FROM contactpersoon
WHERE klant_id = ".$choice."
ORDER BY naam ASC ";
if(!$res_cnt = mysqli_query($mysqli, $sql_cnt)) { include('includes/error_database.php'); die; }
while($row_cnt = mysqli_fetch_array($res_cnt)) {
echo '<option value="'.$row_cnt['id'].'">'.$row_cnt['naam'].'</option>';
}
?>
Use for Seleted object with $("#first-choice option:selected")
<script type="text/javascript">
$("#first-choice").change(function() {
$("#second-choice").load("getter.php?choice=" + $("#first-choice option:selected").val());
});
</script>
Here is my code, which is having a problem displaying the values of the second:
HTML: my form, the first drop down I get the elements from the database with query.
<form name="farmer" action="index.php" method="post">
<label>
<span>Chose Land:</span>
<select name="land" id="land">
<option value="">--land--</option>
<?php
$sql="SELECT `city` FROM `lands`";
$result =mysql_query($sql);
while ($data=mysql_fetch_assoc($result)){
?>
<option value ="<?php echo $data['city'] ?>" ><?php echo $data['city'] ?></option>
<?php } ?>
</select>
</label>
<label>
<span>Region:</span>
<select name="region" id="region">
<option value="">--region--</option>
</select>
</label>
<input class="button4" type="submit" name="submit" value="Submit" />
</form>
JS
jQuery(document).ready(function() {
jQuery('#land').change(function() {
jQuery.post(
'getList.json.php', {
'land': jQuery('#land').val()
},
function(data, textStatus) {
jQuery('#region').empty();
if(data != null)
{
jQuery.each(data, function(index, value) {
jQuery('#region').append('<option value="' + value + '">' + value + '</option>');
});
}
else {
jQuery('#region').append('<option value="">Please select...</option>');
}
},
'json'
);
});
});
getList.json.php file - Here I make connection between region and land with query(JOIN).
<?php
mysql_connect("localhost", "root", "") or die( "Unable to connect to database");
mysql_select_db("farmer_fields") or die( "Unable to select database");
if($_POST && $_POST['land'] != "") {
$sql="SELECT region FROM regions
LEFT JOIN lands
ON regions.id_lands = lands.id";
$rows = array();
while ($data=mysql_fetch_assoc($sql)){
$rows['region'] = $data;
}
echo json_encode( $rows );
}
?>
No need of json here. You can simply do with jquery and ajax
jquery:
function get_region(country_id) {
if (country_id != 0) {
$("#region_id").html("<option value='0'>Select Region</option>");
$("#region_id").prop("disabled", true);
$.post("ajax/ajax.php", {
country_id: country_id
}, function (data) {
var data_array = data.split(";");
var number_of_name = data_array.length - 1;
var value;
var text;
var opt;
var temp_array;
for (var i = 0; i < number_of_name; i++) {
temp_array = data_array[i].split(",");
value = temp_array[1];
//alert(value);
text = temp_array[0];
opt = new Option(text, value);
$('#region_id').append(opt);
$(opt).text(text);
}
$("#region_id").prop("disabled", false);
});
} else {
$("#region_id").html("<option value='0'>Select Region</option>");
$("#region_id").prop("disabled", true);
}
}
ajax file that is ajax.php
if (isset($_POST["country_id"])) {
$country_id = $_POST["country_id"];
$region_select = mysql_query("select * from region where country_id='$country_id'");
$region = "";
$region_id = "";
while ($region_row = mysql_fetch_array($region_select)) {
$region = $region.$region_row["region"].
",".$region_id.$region_row["id"].
";";
}
echo $region;
}
HTML OF REGION SELECT BOX:
<select name="region_id" id="region_id" disabled="disabled">
<option value="0">Select Region</option>
</select>
You may change mysql_query to PDO for security purpose as mysql_query is depriciated.
Check this, works for me.
JS:
jQuery(document).ready(function() {
var region = jQuery('#region');
var land = jQuery('#land').change(function() {
jQuery.post(
'getList.json.php', {
'land': land.val()
},
function(data) {
jQuery('#region').empty();
if (data != null) {
region.append(data);
}
else {
region.append('<option value="">Please select...</option>');
}
},
'html'
);
});
});
PHP:
if($_POST && $_POST['land'] != "") {
$sql="SELECT region
FROM regions r
LEFT JOIN lands l ON r.id_lands = l.id
WHERE l.city = " . $_POST['land'];
$result = mysql_query($sql); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< UPD!
while ($data = mysql_fetch_assoc($result)) {
echo '<option value="' . $data['region'] . '">' . $data['region'] . '</option>';
}
}
i am creating dynamic drop list using php mysql + ajax jquery that the populate of second drop list is based on the selection of the first and third is based on the selection of the second but it did not work can anyone help me ???
dbconfig.php
<?php
$host = "localhost";
$user = "****";
$password = "***";
$db = "lam_el_chamel_db";
?>
select.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#district").attr("disabled","disabled");
$("select#village").attr("disabled","disabled");
$("select#governorate").change(function(){
$("select#district").attr("disabled","disabled");
$("select#district").html("<option>wait...</option>");
$("select#village").attr("disabled","disabled");
$("select#village").html("<option>wait...</option>");
var id = $("select#governorate option:selected").attr('value');
$.post("select_district.php", {id:id}, function(data){
$("select#district").removeAttr("disabled");
$("select#district").html(data);
});
var id2 = $("select#district option:selected").attr('value');
$.post("select_village.php", {id:id}, function(data){
$("select#village").removeAttr("disabled");
$("select#village").html(data);
});
$("form#select_form").submit(function(){
var gover = $("select#governorate option:selected").attr('value');
var dist = $("select#district option:selected").attr('value');
if(gover>0 && dist>0)
{
var result = $("select#district option:selected").html();
$("#result").html('your choice: '+result);
}
else
{
$("#result").html("you must choose two options!");
}
if(dist>0 && village>0)
{
var result = $("select#village option:selected").html();
$("#result").html('your choice: '+result);
}
else
{
$("#result").html("you must choose three options!");
}
return false;
});
});
</script>
</head>
<body>
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a governorate:<br />
<select id="governorate">
<?php echo $opt->ShowGovernorate(); ?>
</select>
<br /><br />
choose a district:<br />
<select id="district">
<option value="0">choose...</option>
</select>
<br /><br />
choose a village:<br />
<select id="village">
<option value="0">choose...</option>
</select>
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
</body>
</html>
select_class.php
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "dbconfig.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowGovernorate()
{
$sql = "SELECT * FROM governorate";
$res = mysql_query($sql,$this->conn);
$governorate = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$governorate .= '<option value="' . $row['governorate_id'] . '">' . $row['governorate_name'] . '</option>';
}
return $governorate;
}
public function ShowDistrict()
{
$sql = "SELECT * FROM districts WHERE governorate_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
var_dump($res);
$district = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$district .= '<option value="' . $row['district_id'] . '">' . $row['district_name'] . '</option>';
}
return $district;
}
public function ShowVillage()
{
$sql = "SELECT village_id, village_name FROM village WHERE district_id=$_POST[id2]";
$res = mysql_query($sql,$this->conn);
$village = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$village .='<option value="' .$row['village_id'] . '">' . $row['village_name'] . '</option>';
}
return $village;
}
}
$opt = new SelectList();
?>
select_district.php
<?php
include "select.class.php";
echo $opt->ShowDistrict();
?>
select_village.php
<?php
include "select.class.php";
echo $opt->ShowVillage();
?>
i think it has something within the select.php but i did not know what is the error
Your ajax call is done on the document.ready function. You should bind the ajax to the dropdown change function like:
$("select#district option:selected").change(function(){
id = $(this).val();
$.post("select_village.php", {id:id}, function(data){
$("select#village").removeAttr("disabled");
$("select#village").html(data);
});
Hope that helps
I am trying to run this tutorial from PHP Jquery cookbook but the First combo box is not populating with country data and it is empty!
I have 4 tables in the database and I have checked them and they are all good!
tables are: Country, States, Towns, and Towninfo
In my html I have:
<html>
<head>
</head>
<body>
<ul>
<li>
<strong>Country</strong>
<select id="countryList">
<option value="">select</option>
</select>
</li>
<li>
<strong>State</strong>
<select id="stateList">
<option value="">select</option>
</select>
</li>
<li>
<strong>Town</strong>
<select id="townList">
<option value="">select</option>
</select>
</li>
</ul>
<p id="information"></p>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('select').change(getList);
getList();
function getList()
{
var url, target;
var id = $(this).attr('id');
var selectedValue = $(this).val();
switch (id)
{
case 'countryList':
if(selectedValue == '') return;
url = 'results.php?find=states&id='+ selectedValue;
target = 'stateList';
break;
case 'stateList':
if($(this).val() == '') return;
url = 'results.php?find=towns&id='+ selectedValue;
target = 'townList';
break;
case 'townList':
if($(this).val() == '') return;
url = 'results.php?find=information&id='+ selectedValue;
target = 'information';
break;
default:
url = 'results.php?find=country';
target = 'countryList';
}
$.get(
url,
{ },
function(data)
{
$('#'+target).html(data);
}
)
}
});
</script>
</body>
</html>
and in the php file I have:
<?php
$mysqli = new mysqli('localhost', 'root', '', 'chain');
$find = $_GET['find'];
switch ($find)
{
case 'country':
$query = 'SELECT id, countryName FROM country';
break;
case 'states':
$query = 'SELECT id, stateName FROM states WHERE countryId='.$_GET['id'];
break;
case 'towns':
$query = 'SELECT id, townName FROM towns WHERE stateId='.$_GET['id'];
break;
case 'information':
$query = 'SELECT id, description FROM towninfo WHERE townId='.$_GET['id'] .' LIMIT 1';
break;
}
if ($mysqli->query($query))
{
$result = $mysqli->query($query);
if($find == 'information')
{
if($result->num_rows > 0)
{
$row = $result->fetch_array();
echo $row[1];
}
else
{
echo 'No Information found';
}
}
else
{
?>
<option value="">select</option>
<?php
while($row = $result->fetch_array())
{
?>
<option value="<?php echo $row[0]; ?>"><?php echo $row[1]; ?> </option>
<?php
}
}
}
?>
According to book the first combobox must be populated after the page has been loaded but the I do not know why it is empty! can you please let me know why this is happening!
Calling:
getList();
after your page loaded won't work as it does not have right context of value "this".
You can try to use:
$('select').trigger("change");
instead of getList(); for first time loading
or another way to try:
$(document).ready(function(){
$('select').change(getList);
getList.call($('select'));
function getList(){...}
}
this should set the right context.(but I'm not 100% sure if it will work, as haven't tried to make fiddle.)