Dropdown that based on another dropdown, select option are from database - javascript

Sorry if it was discussed before, but all of them doesn't really work for me. I have 5 dropdowns they are Brand, Model, Color, Engine No. and Chassis No., My question is what should I do to make the dropdown of the model is based on the selected dropdown of Brand, for example If a user selects Honda well based on my posted image in my database, the BrandID of Honda is 1 so all of the model that has the BrandID = 1. The dropdown of the model shown are only that has a brandID =1. Then the dropdown of color is based on the dropdown of the model, so the same logic like I discussed earlier. Finally the Dropdown of Engine No. and Chasis No. is based on the dropdown of the color, also the same as the logic that I discussed.
Here's my code for the brand dropdown
<label for="bName" class="control-label col-xs-4"><p class="left">Brand</p></label>
<div class="col-xs-7">
<div class="req">
<?php
include_once "config.php";
$bsql="SELECT bName, brandID FROM brand order by bName";
$bstmt=$con->prepare($bsql);
$bstmt->execute();
$bstmt->bind_result($bName, $bid);
$bstmt->store_result();
echo "<select name='brandID' class='form-control'>
<option value=''></option>";
while ($bstmt->fetch()){
echo '<option value="'.$bid.'">'.$bName.'</option>';
}
echo '</select>';
?>
</div>
</div>
Heres the code for the dropdown of the model
<label for="model" class="control-label col-xs-4">
<p class="left">Model</p></label>
<div class="col-xs-7">
<div class="req">
<?php
include_once "config.php";
$msql="SELECT model, modID FROM model order by model";
$mstmt=$con->prepare($msql);
//$mstmt->bind_param('i', $bid);
$mstmt->execute();
$mstmt->bind_result($model, $mid);
$mstmt->store_result();
echo "<select name='mID' class='form-control'>
<option value=''></option>";
while ($mstmt->fetch()){
echo '<option value="'.$mid.'">'.$model.'</option>';
}
echo '</select>';
?>
</div>
</div>
Heres the code for color dropdown
<label for="model" class="control-label col-xs-4"><p class="left">Color</p></label>
<div class="col-xs-7">
<div class="req">
<?php
include_once "config.php";
$csql="SELECT distinct(color) FROM stock order by color";
$cstmt=$con->prepare($csql);
$cstmt->execute();
$cstmt->bind_result($color);
$cstmt->store_result();
echo "<select name='color' class='form-control'>
<option value=''></option>";
while ($cstmt->fetch()){
echo '<option value="'.$color.'">'.$color.'</option>';
}
echo '</select>';
?>
</div>
</div>
Heres the code for the dropdown Engine No.
<label for="engNum" class="control-label col-xs-4">
<p class="left">Engine No</p></label>
<div class="col-xs-7">
<div class="req">
<?php
include_once "config.php";
$esql="SELECT engNum FROM stock where status='Available' order by engNum";
$estmt=$con->prepare($esql);
$estmt->execute();
$estmt->bind_result($engNum);
$estmt->store_result();
echo "<select name='engNum' class='form-control'>
<option value=''></option>";
while ($estmt->fetch()){
echo '<option value="'.$engNum.'">'.$engNum.'</option>';
}
echo '</select>';
?>
</div>
</div>
Heres the code for the dropdown Chasis No.
<label for="chassisNum" class="control-label col-xs-4"><p class="left">Chassis No</p></label>
<div class="col-xs-7">
<div class="req">
<?php
include_once "config.php";
$nsql="SELECT chassisNum FROM stock where status='Available' order by chassisNum";
$nstmt=$con->prepare($nsql);
$nstmt->execute();
$nstmt->bind_result($chassisNum);
$nstmt->store_result();
echo "<select name='chassisNum' class='form-control'>
<option value=''></option>";
while ($nstmt->fetch()){
echo '<option value="'.$chassisNum.'">'.$chassisNum.'</option>';
}
echo '</select>';
?>
</div>
</div>
Heres the Image for my brand database
Heres the Image for my model database
Heres the Image for the color, chasis no. and engine no. database

Write an onchange event on select tag
for e.g. to change the Models based on brand selected you should write
<label for="bName" class="control-label col-xs-4"><p class="left">Brand</p></label>
<div class="col-xs-7">
<div class="req">
<?php
include_once "config.php";
$bsql="SELECT bName, brandID FROM brand order by bName";
$bstmt=$con->prepare($bsql);
$bstmt->execute();
$bstmt->bind_result($bName, $bid);
$bstmt->store_result();
echo "<select name='brandID' class='form-control' **onchange='getModels(this)'**>
<option value=''></option>";
while ($bstmt->fetch()){
echo '<option value="'.$bid.'">'.$bName.'</option>';
}
echo '</select>';
//The function getModels(this) will get called whenever user will change the value of the brand option.
Now define this method in your js file
function getModels(BrandObj)
{
brandValue=BrandObj.value; // Will give you the ID of brand which is selected.
// Make A ajax call to some php file which will return models based on brand ID & bind it to your Models Dropdown
$.ajax({
url: 'getModels.php',
type: 'GET', // Method Type
data: 'brandID=brandValue',// This parameter will be sent to getModels.php
success: function(**data**) {
//called when successful the data we have returned in getModels.php will be accessible in "data" variable
// Decode the response & bind it to your dropdownList
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
}
// IN your getModels.php file write following code
$BrandID=#$_GET['brandID'];
//Connect to database
// Write a sql to find models having brand_id=$BrandID
// Fetch rows & create array of Models & return it using
echo json_encode(*your_array_name*)
// END getModels.php
// You can find the detailed documentation of AJAX
http://api.jquery.com/jquery.ajax/

Related

Passing option id from select element to form submission

I'm using a select form element to render multiple options and then show corresponding text from a database in the text area using an onchange event.
The value of the select option's are very long, so I'd like to pass the id, or name of the option, to my form target favorite.php, but I don't know how to do it.
HTML:
<div class="container">
<div class="had">
<form name="det" action="vispage.php" method="POST">
<label for="hadeath">Selct Title of the Hadeath</label>
<select name="header" onchange="document.getElementById('txt').innerHTML=this.value">
<?php foreach($hadeeth as $i) {?>
<option id="<?php echo $i['id']; ?>" value="<?php echo $i['short']; ?>"><?php echo $i['name']; ?></option>
<?php } ?>
</select><br><br>
<label for="a">tree :</label><br>
<textarea id="txt" name="tree" rows="15" cols="30"></textarea><br><br>
Add to Favorites </form>
</div>
</div>
PHP:
<?php
$title = "hadeeth";
include_once ("header.php");
include 'connect.php';
//CREATE THE QUERY
$query = "SELECT * FROM `search`";
//RUN THE QUERY
$result = mysqli_query($con,$query);
$hadeeth = array();
// RETRIEVE VALUES FROM RESULT
while($row = mysqli_fetch_assoc($result))
{
$hadeeth[$row['name']] = array(
'id'=>$row['id'],
'name'=>$row['name'],
'short'=>$row['short']
);
}
?>

Can't $_GET or $_POST Dynamic Drop Down Variables

JavaScript
// JQuery script is on ajax.php page
// JQUERY PIECE TO PROCESS STATE AND CITY VALUES
// BASED ON COUNTRY SELECTION
function change_CountryNo() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "ajax.php?CountryNo=" + document.getElementById("CountryNodd").value, false);
xmlhttp.send(null);
document.getElementById("StateID").innerHTML = xmlhttp.responseText;
if (document.getElementById("CountryNodd").value == "CountryNo") {
document.getElementById("CityID").innerHTML = "<select><option>City</option></select>";
}
}
function change_StateID() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "ajax.php?StateID=" + document.getElementById("StateIDdd").value, false);
xmlhttp.send(null);
document.getElementById("CityID").innerHTML = xmlhttp.responseText;
if (getElementById("StateIDdd").value == "StateID") {
document.getElementById("CityID").innerHTML = "<select><option>City</option></select>";
}
}
<!DOCTYPE html>
<html>
<head>
<!-- index.php -->
<!-- THIS CODE PROVIDES A DROP DOWN FORM
FOR USER TO SELECT COUNTRY THEN STATE THEN CITY
A JQUERY SCRIPT PROCESSES THE COUNTRY VALUE
TO PRODUCE THE APPROPRIATE STATES AND
PROCESSES THE STATE VALUE TO PRODUCE
THE APPROPRIATE CITIES -->
<title>Country, State, City Selection</title>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<!-- THESE FILES ARE DATABASE CONNECTION AND FUNCTIONS
FOR VARIOUS LOGIN, USER SESSION VARIABLES TO IDENTIFY
THE CONTACT NO OF USER UPDATING THEIR LOCATION -->
<?php include("includes/header.php") ?>
<?php include("includes/nav.php") ?>
<?php //Check user's login status
if (logged_in() === false) {
echo "Redirecting...";
redirect("../index.html");
}
?>
<!-- responsive setup for form -->
<div class="row">
<div class="col-lg-6 col-lg-offset-3">
</div>
</div>
<!-- end of class row div -->
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-login">
<div class="panel-heading">
<div class="row">
<div class="col-xs-12">
<div class="col-xs-6">
</div>
<div class="col-xs-6">
Country-State-City Selection
</div>
</div>
<hr>
</div>
<!-- end of class row div -->
<div class="panel-body">
<div class="row col-md-12" style="text-align: center">
<form method="POST" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>" autocomplete="off">
<div id="CountryNo" class="col-xs-3 form-group" style="font-size: 75%">
<select id="CountryNodd" name="CountryNodd" onChange="change_CountryNo()" class="form-control selectpicker" style="width:100%;">
<option>Country</option>
<?php
$res=mysqli_query($con, "SELECT * FROM countries ORDER BY Country_Descrip");
while($row=mysqli_fetch_array($res))
{
?>
<option value="<?php echo $row["CountryNo"]; ?>"><?php echo $row["Country_Descrip"]; ?></option>
<?php $CountryNodd = $_POST["CountryNo"]; ?>
<?php }
?>
</select>
</div>
<div id="StateID" class="col-xs-3 form-group" style="font-size: 75%">
<select id="StateIDdd" name="StateID" class="form-control selectpicker" style="width:100%;">
<option>Product</option>
</select>
</div>
<div id="CityID" class="col-xs-3 form-group" style="font-size: 75%">
<select id="CityIDdd" name="CityIDdd" class="form-control selectpicker" style="width:100%;">
<option>Brand</option>
</select>
</div>
<div class="form-group">
<img src="img\..." class="img-responsive" alt="Country-State-City Image" width="100%" height="auto">
<div class="col-lg-12 text-center">
<br>
<input type="submit" name="reset" id="reset" tabindex="3" class="form-control btn btn-register" value="Reset Country-State-City Selections" required>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 text-center">
<br>
<input type="submit" name="Update My Country-State-City" id="update" tabindex="4" class="form-control btn btn-register" value="Update My Country-State-City" required>
</div>
</div>
</form>
<!-- end of form -->
</div>
<!-- end of row col-md-12 div -->
</div>
<!-- end of panel-body div -->
</div>
<!-- end of panel-heading div -->
</div>
<!-- end of panel-login div -->
</div>
<!-- end of col-md-6 col-md-offset-3 div -->
</div>
<!-- end of class row div -->
<!-- ajax.php -->
<!DOCTYPE HTML>
<html>
<head>
<title>ajax.php</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<?php
//THIS FILE PROCESSES THE JQUERY SELECT BASED ON COUNTRY INPUT AND
//THE STATE INPUT
// Turn off error reporting
error_reporting(0);
$con=mysqli_connect('localhost', 'root', '', 'contact_info');
mysqli_set_charset($con,"utf8");
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
// Get the Country and State Values User Selects
$CountryNo=$_GET["CountryNo"];
$StateID=$_GET["StateID"];
//Check user selection for country and list states
if($CountryNo!="Country")
{
$query="SELECT State_ID, StateCountry_ID, State_Description FROM states WHERE StateCountry_ID=$CountryNo ORDER BY State_Description";
$result=mysqli_query($con, $query);
echo "<select id='StateIDdd' onchange='change_StateID()' selected>";
echo "<option>"; echo "State"; echo "</option>";
while($row=mysqli_fetch_array($result))
{
echo "<option value='$row[State_ID]'>"; echo $row["State_Description"]; echo "</option>";
}
echo "</select>";
}
//Check user selection for state and list cities
if($StateID!="State")
{
$query="SELECT CityID, City_Name, CountryNo, CityState_ID FROM cities WHERE CityState_ID=$StateID ORDER BY City_Name";
$result=mysqli_query($con, $query);
echo "<select>";
while($row=mysqli_fetch_array($result))
{
echo "<option value='$row[CityID]' selected>"; echo $row["City_Name"]; echo "</option>";
}
echo "</select>";
}
?>
<?php include("ajax2.php") //Go to post to MySQL processing
?>
</head>
</html>
<!-- ajax2.php -->
<!-- THIS FILE POSTS THE COUNTRY, STATE, CITY VALUES TO
MYSQLI AND UPDATES THE USER'S CONTACT LOCATION -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<?php include("includes/header.php") ?>
<?php include("includes/nav.php") ?>
<?
// Turn off error reporting
error_reporting(0);
$con=mysqli_connect('localhost', 'root', '', 'contact_info');
mysqli_set_charset($con,"utf8");
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
?>
<?
// Ensure user is logged in to get values
// for ContactNo
php if (logged_in() === false) {
echo "Redirecting...";
redirect("../index.html");
}
//store country, state, city selection and update contact's location
$CountryNo = $_POST['CountryNodd'];
$StateID = $_POST['StateIDdd'];
$CityID = $_POST['CityIDdd'];
//Update MySQL
$sql = "UPDATE contact_location SET CountryNodd=$CountryNo, StateID=$StateID, CityID=$CityID";
$sql.= "WHERE ContactNo=$ContactNo"; //Contact info is from contact table accessed via function include in header.php
$res_update = mysqli_query($con,$sql);
if($res_update) {
echo "Location updated successfully";
}
else {
echo "Not working...";
}
?>
I've read related questions/responses, but none resolve my problem.
I am very new to jQuery & PHP programming with a MySQL backend.
Created a 3-level drop down (Country-State-City) form where users
can select country-state-city values, which will update
MySQL.
While I can GET and POST the Country variable, I have been
unsuccessful for State and City. I can see the correct value of
the State variable, but I do not see a value for the City variable.
Furthermore, I cannot POST either the State or City variables: I get an
"Index Undefined" error for the variables associated with each.
SOLVED: The POST execution was occurring before the JavaScript actions, and this is because PHP, server side, is executed before Java, client-side. I moved the MySQL update code into the PHP script at the point the City selection has occurred.
I will not provide the code because comments I received thus far suggest my documentation needs work. Certainly appreciate that feedback and will take steps to improve future posts. Thank you!

unable to fetch data in multiple dropdown

I am unable to fetch the data in the second dropdown(which is depended upon the first dropdown). e.g. when we select country then the relevant state should be displayed but it doesn't. see my code.
my html
<?php
require 'dbconfig.php';
?>
<label class="control-label">Select Distict</label>
<div class="form-group">
<div class="col-lg-6">
<select class="form-control" name=dist id=dist>
<option value='' selected>Select</option>
<?Php
$ddObj = new USER($DB_con);
$table= "tbl_dist";
$sel = $ddObj->dropdowndist($table);
foreach ($sel as $val) {
echo "<option value=$val[dist_id]>$val[dist_name]</option>";
}
?>
</select>
</div>
</div>
<label class="control-label">Select Block</label>
<div class="form-group">
<div class="col-lg-6">
<select class="form-control" name=block id=block>
</select>
</div>
</div>
my jquery
<script>
$(document).ready(function() {
$('#dist').change(function(){
var dist_id=$('#dist').val();
$('#block').empty(); //remove all existing options
$.get('ddblock.php',{'dist_id':dist_id},function(return_data){
$.each(return_data.data, function(key,value){
$("#block").append("<option value='" + value.block_id +"'>"+value.block_name+"</option>");
});
}, "json");
});
});
</script>
ddblock.php
<?Php
$dist_id=$_GET['dist_id'];
if(!intval($dist_id)){
echo "Data Error";
exit;
}
require 'class.user.php';
$ddObj = new USER($DB_con);
$table = "tbl_block";
$result = $ddObj->fetch_block($table,$dist_id);
$main = array('data'=>$result);
echo json_encode($main);
}
?>
class.user.php
public function fetch_block($table,$dist_id){
try
{
$sel = $this->db->prepare("SELECT * FROM $table WHERE block_dist_id=:dist_id");
$sel->bindValue(':dist_id', $dist_id);
$sel->execute();
$rs = $sel->setFetchMode( PDO::FETCH_ASSOC );
return $sel;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}

Dynamic Dropdown Menu [PHP]

I'm trying to create a two dropdown that are dynamics, by selecting an option, it changes the other one, just like the Country and Cities examples we see in websites nowadays, but in my case, I want by selecting a Store, it shows all the franquises. I don't know why it's not working.
Here's the code:
<div class="row wow fadeInRight">
<div class="col-sm-3 col-sm-offset-2">
<form action="#">
<div class="form-group">
<label id="drops-labels"><b id="centraliza-txt">Store</b></label>
<span data-toggle="tooltip" data-placement="top" title="Choose a Store">
<?php echo "<select class='form-control input-sm' name='store' id='store-list' onChange='pickFranch(this.value)'>";
echo "<option value='0'>---Select---</option>";
while($dadosRedes = mysql_fetch_array($buscarDadosSuperv)) {
echo "<option value='".$dadosRedes['Store']."'>".$dadosRedes['Store']."</option>";
}
echo "</select>";
?>
</span>
</div>
</form>
</div>
<div class="col-sm-3">
<label id="drops-labels"><b id="centraliza-txt">Franchise</b></label>
<select name="franch" id="franch-list" class='form-control input-sm'">
<option value="0">---Select---</option>
</select>
</div>
<script>
function pickFranch(val) {
$.ajax({
type: "POST",
url: "ajaxPickStore.php",
data: // i dont know what to put here
success: function(data){
$("#lojas-list").html(data);
}
});
}
</script>
AjaxPickStore.php
<?php session_start();
require_once("connect.php");
$db_handle = new DBController();
if(!empty($_POST["store_id"])) {
$query ="SELECT Loja FROM indicadores_rv_m1 WHERE store = '".$_POST['store_id']."' and Supervisor = '".$_SESSION['usuarioNome']."'";
$results = $db_handle->runQuery($query);
?>
<option value="0">---Select---</option>
<?php
foreach($results as $franch) {
?>
<option value="<?php echo $franch["franch"]; ?>"><?php echo $franch["franch"];?></option>
<?php
}
}
?>
I barely know Ajax, so if you could explain the synthax also, it'd help me a lot!
Ty

populating a 2nd select box based off the 1st one using ajax and PHP

I'm going a little nuts here. I know this has been answered a few times before but I can't seem to get it. I must be missing something very obvious.
I need the options of the second select input to be dynamically populated from a DB based on selection of the 1st select input. I have tested the getShowByBand.php code and it produces the intended results. My guess is the problem lies in the javascript file. Please take a look at my code and see if you can help.
testForm.php
<form role="form">
<div class="well" id="generalIDRows">
<div class="row">
<div class="col-md-6 padding-top-10">
<div class="form-group">
<label for="band">Choose Band:</label>
<select id="band" name="band" class="form-control">
<option value="">Band Name</option>
<?php
$sql = "SELECT bandID,bandName FROM Band";
$bandq = mysqli_query($link, $sql);
while($row = mysqli_fetch_array($bandq))
{
$band_ID=$row["bandID"];
$band=$row["bandName"];
echo '<option value="' . $band_ID . '">' . $band .'</option>';
}
?>
</select>
<script src="js/getShowByBand.js" type="text/javascript"></script>
</div>
</div>
<div class="col-md-6 padding-top-10">
<div class="form-group">
<label for="show">Choose Show:</label>
<select id="show" name="show" class="form-control">
<option value="">--Select Show--</option>
</select>
</div>
</div>
</div>
</div>
</form>
getShowByBand.js
$(document).ready(function()
{
$(".band").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "womhScripts/getShowByBand.php",
data: dataString,
cache: false,
success: function(html)
{
$(".show").html(html);
}
});
});
});
getShowByBand.php
<?php
$link=mysqli_connect("localhost","womhproduction","Derkadeepd0ng","womh");
if (mysqli_connect_errno())
echo "failed to connect" . mysqli_connect_error();
if($_POST)
{
$id=$_POST['id'];
$showSQL = mysqli_query($link,"SELECT showID FROM Act WHERE bandID =" . $id . ";");
$showResults = mysqli_num_rows($showSQL);
if($showResults > 0)
{
echo "<option selected disabled>--Select show--</option>";
while($showRow = mysqli_fetch_array($showSQL))
{
$showID= $showRow['showID'];
$showNameSQL = mysqli_query($link, "SELECT showName FROM Shows WHERE showID=". $showID . ";");
$showNameResults = mysqli_num_rows($showNameSQL);
if($showNameResults > 0)
{
while($showNameRow = mysqli_fetch_array($showNameSQL))
{
$showName = $showNameRow['showName'];
echo '<option value= "' . $showID . '">' . $showName . '</option>';
}
}
}
}
}
?>
Use $("#band").change... dot is used to select class.
try to change this $(".band") to this $("#band") on your javascript you are calling on change for the class you should do it by id.

Categories

Resources