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>
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 want to add part search into a website powered by WordPress. I have currently achieved the function, but I have trouble of integrating it into WordPress. I tried several ways but the dynamic dependent select box still not working.
I followed this tutorial: Dynamic Dependent Select Box using jQuery, Ajax and PHP
Below are my code which works well outside WordPress.
index.php
<head>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="js/ajax-ps.js"></script>
</head>
<body>
<form class="select-boxes" action="ps-result.php" method="POST">
<?php
include('dbConfig.php');
$query = $db->query("SELECT * FROM ps_manufact WHERE status = 1 ORDER BY manufact_name ASC");
$rowCount = $query->num_rows;
?>
<select name="manufacturer" id="manufact" class="col-md-2 col-sm-2 col-xs-10" onchange="manufactText(this)">
<option value="">Select Manufacturer</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['manufact_id'].'">'.$row['manufact_name'].'</option>';
}
}else{
echo '<option value="">Manufacturer Not Available</option>';
}
?>
</select>
<input id="manufacturer_text" type="hidden" name="manufacturer_text" value=""/>
<script type="text/javascript">
function manufactText(ddl) {
document.getElementById('manufacturer_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="type" id="type" class="col-md-2 col-sm-2 col-xs-10" onchange="typeText(this)">
<option value="">Select Manufacturer First</option>
</select>
<input id="type_text" type="hidden" name="type_text" value=""/>
<script type="text/javascript">
function typeText(ddl) {
document.getElementById('type_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="year" id="year" class="col-md-2 col-sm-2 col-xs-10" onchange="yearText(this)">
<option value="">Select Type First</option>
</select>
<input id="year_text" type="hidden" name="year_text" value=""/>
<script type="text/javascript">
function yearText(ddl) {
document.getElementById('year_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="model" id="model" class="col-md-2 col-sm-2 col-xs-10" onchange="modelText(this)">
<option value="">Select Year First</option>
</select>
<input id="model_text" type="hidden" name="model_text" value=""/>
<script type="text/javascript">
function modelText(ddl) {
document.getElementById('model_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<input type="submit" name="search" id="search" class="col-md-2 col-sm-2 col-xs-10" value="Search">
</form>
</body>
ajax-ps.js
$(document).ready(function(){
$('#manufact').on('change',function(){
var manufactID = $(this).val();
if(manufactID){
$.ajax({
cache: false,
type:'POST',
url:'ajax-data.php',
data:'manufact_id='+manufactID,
success:function(type_data){
$('#type').html(type_data);
$('#year').html('<option value="">Select Type First</option>');
}
});
}else{
$('#type').html('<option value="">Select Manufact First</option>');
$('#year').html('<option value="">Select Type First</option>');
}
});
$('#type').on('change',function(){
var typeID = $(this).val();
if(typeID){
$.ajax({
cache: false,
type:'POST',
url:'ajax-data.php',
data:'type_id='+typeID,
success:function(year_data){
$('#year').html(year_data);
$('#model').html('<option value="">Select Year First</option>');
}
});
}else{
$('#year').html('<option value="">Select Type First</option>');
$('#model').html('<option value="">Select Year First</option>');
}
});
$('#year').on('change',function(){
var yearID = $(this).val();
if(yearID){
$.ajax({
cache: false,
type:'POST',
url:'ajax-data.php',
data:'year_id='+yearID,
success:function(model_data){
$('#model').html(model_data);
}
});
}else{
$('#model').html('<option value="">Select Year First</option>');
}
});
});
ajax-data.php
include('dbConfig.php');
if(isset($_POST["manufact_id"]) && !empty($_POST["manufact_id"])){
$query = $db->query("SELECT * FROM ps_type WHERE manufact_id = ".$_POST['manufact_id']." AND status = 1 ORDER BY type_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Type</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['type_id'].'">'.$row['type_name'].'</option>';
}
}else{
echo '<option value="">Type Not Available</option>';
}
}
if(isset($_POST["type_id"]) && !empty($_POST["type_id"])){
$query = $db->query("SELECT * FROM ps_year WHERE type_id = ".$_POST['type_id']." AND status = 1 ORDER BY year_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Year</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['year_id'].'">'.$row['year_name'].'</option>';
}
}else{
echo '<option value="">Year Not Available</option>';
}
}
if(isset($_POST["year_id"]) && !empty($_POST["year_id"])){
$query = $db->query("SELECT * FROM ps_model WHERE year_id = ".$_POST['year_id']." AND status = 1 ORDER BY model_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Model</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['model_id'].'">'.$row['model_name'].'</option>';
}
}else{
echo '<option value="">Model Not Available</option>';
}
}
Now the problem is, when select the first box, the second one becomes empty, nothing is returned from the database:
Capture - After select the first box
Really appreicate Christos Lytras to help me solve the previous problem.
I have a new problem with action="ps-result.php" in the line <form class="select-boxes" action="ps-result.php" method="POST">.
ps-result.php
<?php
if (isset($_POST['search'])) {
$clauses = array();
if (isset($_POST['manufacturer_text']) && !empty($_POST['manufacturer_text'])) {
$clauses[] = "`manufacturer` = '{$_POST['manufacturer_text']}'";
}
if (isset($_POST['type_text']) && !empty($_POST['type_text'])) {
$clauses[] = "`type` = '{$_POST['type_text']}'";
}
if (isset($_POST['year_text']) && !empty($_POST['year_text'])) {
$clauses[] = "`year` = '{$_POST['year_text']}'";
}
if (isset($_POST['model_text']) && !empty($_POST['model_text'])) {
$clauses[] = "`model` = '{$_POST['model_text']}'";
}
$where = !empty( $clauses ) ? ' where '.implode(' and ',$clauses ) : '';
$sql = "SELECT * FROM `wp_products` ". $where;
$result = filterTable($sql);
}
else {
$sql = "SELECT * FROM `wp_products` WHERE `manufacturer`=''";
$result = filterTable($sql);
}
function filterTable($sql) {
$con = mysqli_connect("localhost", "root", "root", "i2235990_wp2");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$filter_Result = mysqli_query($con, $sql);
return $filter_Result;
}
?>
<?php get_header(); ?>
<div class="container">
...
</div>
<?php get_footer(); ?>
Now when I click Search, it returns
Fatal error: Call to undefined function get_header() in /Applications/MAMP/htdocs/wordpress/wp-content/themes/myTheme/inc/ps-result.php on line 42.
The proper way to do this, is to create a wordpress shortcode and then use that shortcode wherever you want, page or post, but if you want to create something more specific, then you should create a small wordpress plugin. I won't get into this, but it’s really not a big deal to create a simple wordpress plugin having such functionality. I’ll go through the steps on how you can have this working in wordpress with the files and the code you already have.
I assume you already have the tables of your example created. My tables are like this:
wp_citytours_dynsel_cities
wp_citytours_dynsel_states
wp_citytours_dynsel_countries
I have imported some data and I have all those tables filled with proper data. I can provide some sql files if you like, but I assume you already have your tables filled with the proper data for each table.
My test theme root directory is:
/wp-content/themes/citytours/
I have created the directory under my theme root directory and I have included all the code files there, so we have 3 files:
/wp-content/themes/citytours/dynsel/index-partial.php
<?php
//Include database configuration file
include('dbConfig.php');
//Get all country data
$query = $db->query("SELECT * FROM wp_citytours_dynsel_countries WHERE status = 1 ORDER BY country_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
?>
<select name="country" 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 name="state" id="state">
<option value="">Select country first</option>
</select>
<select name="city" id="city">
<option value="">Select state first</option>
</select>
<script type="text/javascript">
jQuery(function($) {
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/citytours/dynsel/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:'<?php echo home_url('wp-content/themes/citytours/dynsel/ajaxData.php') ?>',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
/wp-content/themes/citytours/dynsel/dbConfig.php
<?php
//db details
$dbHost = 'localhost';
$dbUsername = 'xxxx';
$dbPassword = 'xxxx';
$dbName = 'xxxx';
//Connect and select the database
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
/wp-content/themes/citytours/dynsel/ajaxData.php
<?php
//Include database configuration file
include('dbConfig.php');
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
//Get all state data
$query = $db->query("SELECT * FROM wp_citytours_dynsel_states WHERE country_id = ".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//Display states 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>';
}
}
if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
//Get all city data
$query = $db->query("SELECT * FROM wp_citytours_dynsel_cities WHERE state_id = ".$_POST['state_id']." AND status = 1 ORDER BY city_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//Display cities 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>';
}
}
?>
As you can see, the index-partial.php now contains only needed code, without <body>, <head> and script files included. Wordpress already includes jQuery to the application for most themes, but you should always check that.
Now, you can add the functionality wherever you want, even at the theme index.php file, but always with caution. I have used theme's single post template file, which is single-post.php. I have included the example code, under the main post body inside a div. I just include the index-partial.php like this:
<div class="<?php echo esc_attr( $content_class ); ?>">
<div class="box_style_1">
...
</div><!-- end box_style_1 -->
<div class="box_style_1">
<?php include(__DIR__.'/dynsel/index-partial.php'); ?>
</div>
</div><!-- End col-md-9-->
I also have used the wordpress home_url function, to have a proper url rooted for the ajaxData.php file like this:
url:'<?php echo home_url('wp-content/themes/citytours/dynsel/ajaxData.php') ?>'
Now, if you have followed all these steps, then you should have your code example working at under each post. You can now included it wherever you want by using that line of code <?php include(__DIR__.'/dynsel/index-partial.php'); ?>.
Please let me know if that worked for you.
I have this select , i wanna save each value after change , save it and use in other select
This is my code :
<?
$sql = "SELECT * FROM championnat ";
$result = $conn->query(sprintf($sql));
if($result){
if ($result->num_rows != 0)
{
$rows=array();
?>
<select name="nom_championnat" id="nom_championnat" >
<option value=""></option>
<?php
while($r=mysqli_fetch_assoc($result))
{
?>
<option value=" <?php echo $r['idChampionnat']?>" name="nom_championnat" selected >
<?php echo $r['nomChampionnat'] ?></option>
<?php
}
}
}
?>
</select>
</div>
I need the variable $r['idChampionnat'] to save it in each select and use it in this requete , how can it asve and put it in that requete sql ????
<?php
$sql = "SELECT * FROM equipe where idChampionnat=???? ";
$result = $conn->query(sprintf($sql));
if($result){
if ($result->num_rows != 0)
{
$rows=array();
?>
<select name="equipe1" >
<option value=""></option>
<?php
while($r=mysqli_fetch_assoc($result))
{
?>
<option required value=" <?php echo $r['nomEquipe']?>" name="equipe1" selected ><?php echo $r['nomEquipe'] ?>
</option>
<?php
}
}
}
?>
</select>
just to clear it ,
You need to use jQuery to fire an AJAX call when the first box is selected.
Its been a while since I've done this but this should give you some idea. I took some code from here and here as example
Say your html looks like this
<select id="nom_championnat">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select id="equipe1"></select>
then you need to tell jquery what to do when nom_championnat changes selection
$('#nom_championnat').change(function() {
var data = "";
$.ajax({
type:"POST",
url : "queryfile.php",
data : "value="+$(this).val(),
async: false,
success : function(response) {
data = response;
return response;
},
error: function() {
alert('Error occured');
}
});
var string = data.message.split(",");
var array = string.filter(function(e){return e;});
var select = $('equipe1');
select.empty();
$.each(array, function(index, value) {
select.append(
$('<option></option>').val(value).html(value)
);
});
});
and then you need a queryfile.php to handle the ajax requests, something like
<?php
print_r($_POST);
$value = $_POST["value"];
$sql = "select where {$value} ..."
$result = execute($sql);
echo $result;
?>
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() {
I am trying to populate second dropdown list based on first dropdown list selection using Ajax, jQuery, PHP and MySQL. The problem is the options in second dropdown list just appears in one line (all options in one line)!
I was hoping the while loop inside the results.php could handle this but it seems not. How can I fix this issue?
Here is my code:
<html>
<body>
<?php
$mysqli = new mysqli('localhost', 'root', '', 'chain');
if ($mysqli->connect_errno)
{
die('Unable to connect!');
}
else
{
$query = 'SELECT * FROM Cars';
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
?>
<p>
Select a Car
<select id="selectCar">
<option value="select">Please Select From The List</option>
<?php
while($row = $result->fetch_assoc())
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['title']; ?></option>
<?php
}
?>
</select>
</p>
<select>
<option value="select">Please Select From The List</option>
<option id="result"></option>
</select>
<?php
}
else
{
echo 'No records found!';
}
$result->close();
}
else
{
echo 'Error in query: $query. '.$mysqli->error;
}
}
$mysqli->close();
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#selectCar').change(function()
{
if($(this).val() == '') return;
$.get(
'results.php',
{ id : $(this).val() },
function(data)
{
$('#result').html(data);
}
);
});
});
</script>
</body>
</html>
In the PHP result I have:
<?php
$mysqli = new mysqli('localhost', 'root', '', 'chain');
$resultStr = '';
$query = 'SELECT * FROM models WHERE carID='.$_GET['id'];
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$resultStr.= '<option value="'.$row['id'].'">'.$row['model'].'</option>';
}
}
else
{
$resultStr = 'Nothing found';
}
}
echo $resultStr;
?>
You should edit your script into this..
<select id="result">
<option value="select">Please Select From The List</option>
</select>
You are setting $('#result').html(data); in the main file.
result should be the id of the HTML select element, you used it as id for the an option element.
(You are appending the values into the option element, which doesn't create new HTML elements, but they should be inserted into the select element.)