selecting related data from database with select option, php mysql - php

Database Table "Product" has a "Product_Code" and "Product_Name"
We have a form where we fill Product Data
Select options are fetched from Database table column "Product_Code"
<select name="Select_Product_Code" id="Select_Product_Code">
<option value="0">Product</option>
<?php
$con = mysqli_connect('localhost','user1db','userdb','1db');
if (!$con) { die('Could not connect: ' . mysqli_error($con)); }
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM Product";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
?>
<option value = "<?php echo($row['Product_Code'])?>" >
<?php echo($row['Product_Code']);
?>
</option>
<?php
}
?>
</select>
Without Form submit, Is there a way to show "Product_Name" in a Label or TextInput when "Product_Code" is selected ?
Edit , added ajax.
readproduct.php
<!DOCTYPE html>
<html>
<head>
<script>
function showProduct(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getproduct.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="products" onchange="showProduct(this.value)">
<option value="">Select </option>
<option value="1">0001</option>
<option value="2">0002</option>
<option value="3">0003</option>
<option value="4">0004</option>
</select>
</form>
<br>
<div id="txtHint"><b>list</b></div>
</body>
</html>
getproduct.php as follows
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','user1db','userdb','1db');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
echo "Connected";
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM Stock WHERE Product_Code = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo $row['Product_Name'];
}
mysqli_close($con);
?>
If we remove where clause, all products names are displayed,
with where clause, getproduct.php does not display Product_Names.
What we missed or did wrong?

You can populate an array inside your while loop that will be used later in a change listener for the select element like so:
<select name="Select_Product_Code" id="Select_Product_Code">
<option value="0">Product</option>
<?php
$con = mysqli_connect('localhost','user1db','userdb','1db');
if (!$con) { die('Could not connect: ' . mysqli_error($con)); }
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM Product";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
// here it adds a name with a key that matches the option-value
$names[$row['Product_Code']] = $row['Product_Name'];
?>
<option value = "<?php echo($row['Product_Code'])?>" >
<?php echo($row['Product_Code']);
?>
</option>
<?php
}
?>
</select>
<input type="text" id="out-text" value="The Name will appear here" />
<!-- then it populates the array with json_encode() to be used in the event-listener (both below) -->
<script type="text/javascript">
var names = <?php echo json_encode($names); ?>;
document.getElementById("Select_Product_Code").addEventListener(
'change',
function() {
document.getElementById("out-text").value = names[this.selectedIndex];
},
false
);
</script>
This is not the only way to do it, but its vanilla javascript/php, and here is a JSFiddle with the basic logic (minus the PHP part)

Related

Integrating dynamic dependent select box into WordPress

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.

Select value from drop down list and second drop down list auto changed

I have one table in my database called as company and inside company table there are 3 columns name Id,Company_Name and location.
I have two drop down list. First drop down list displaying only Company name and according to company name location will change in second drop down list.
I did some code but in second drop down i am getting all location name.
<?php
//$comp=$_POST['Company'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demo_db";
//open connection to mysql db
$connection = mysqli_connect($servername,$username,$password,$dbname) or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from company";// it displaying all company name in my first drop down list
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
if (isset($_POST['Company'])) {
$name=$_POST['Company'];
$sql = "select * from company where Company_name=$name";
}
$result_loc = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//close the db connection
mysqli_close($connection);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<select onchange='this.form.submit();' name="Company">
<option value="Select your Location1" disabled selected>Select your company</option>
<?php while($row = mysqli_fetch_array($result)):;?>
<option value="<?php echo $row[1];?>"><?php echo $row[1];?></option>
<?php endwhile;?>
</select>
<select>
<option value="" disabled selected>Select your location</option>
<?php while($row = mysqli_fetch_array($result_loc)):;?>
<option value="<?php echo $row[2];?>"><?php echo $row[2];?></option>
<?php endwhile;?>
</select>
</body>
</html>
To aid you in chaining SELECT menus using ajax the following might prove useful - you should be able to modify this to suit your db structure and naming conventions. You can run this "as-is" to see the results - hope it will prove useful.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) ){
$action=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
$id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );
if( $action && $id && !is_nan( $id ) ){
$sql='select * from table where id=?';
/* etc ~ generic sql example only ! */
/* query db*/
/* process recordset and build menu data */
/*
demo response sent back to aajx callback
In reality this would be dynamically generated with
results from the db query above.
*/
for( $i=0; $i < 10; $i++ )echo "<option value='Location-$id-$i'>Location-$id-$i";
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>Dependent / Chained SELECT menus</title>
<script type='text/javascript' charset='utf-8'>
/* Basic Ajax function */
function ajax(m,u,p,c,o){
/*
m=Method,
u=Url,
p=Params,
c=Callback,
o=Options
*/
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
};
var params=[];
for( var n in p )params.push(n+'='+p[n]);
switch( m.toLowerCase() ){
case 'post': p=params.join('&'); break;
case 'get': u+='?'+params.join('&'); p=null; break;
}
xhr.open( m.toUpperCase(), u, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( p );
}
/* Callback function to populate second menu */
function createmenu(r,o,h){
/*
r=response
o=options ( sent by ajax function )
h=response headers
*/
o.menu.innerHTML=r;
}
function bindEvents(){
/* Get references to the two dropdown menus */
var oSelCompany=document.querySelectorAll('select[name="Company"]')[0];
var oSelLocation=document.querySelectorAll('select[name="Locations"]')[0];
/* Assign an `onchange` event listener */
oSelCompany.onchange=function(e){
var method='post';
var url=location.href;
/* the parameters to send to the PHP script */
var params={
'action':'getmenu',
'id':this.options[ this.options.selectedIndex ].value
};
/* Options to pass to the ajax callback */
var opts={
menu:oSelLocation
};
/* make the ajax request */
ajax.call( this, method, url, params, createmenu, opts );
}.bind( oSelCompany );
}
document.addEventListener( 'DOMContentLoaded', bindEvents,false );
</script>
<style type='text/css' charset='utf-8'>
select {padding:1rem;width:300px;}
</style>
</head>
<body>
<form method='post'>
<select name='Company'>
<option value=1>One
<option value=2>Two
<option value=3>Three
<option value=4>Four
<option value=5>Five
</select>
<select name='Locations'></select>
</form>
</body>
</html>
I have created a Demo for you. suppose you have company name and company has multiple location Example (id,name,location) :1,TCS,Banglore 2,TCS,Hyderabad
<?php
/*database connection*/
$con = mysqli_connect("localhost","root","root","search");
?>
<script>
function test(name)
{
// new file name f1.php
var strURL = "f1.php?name="+name;
var ax=new XMLHttpRequest();
ax.onreadystatechange = function()
{
if(ax.readyState==4){
document.getElementById("myid").innerHTML = ax.responseText;
}
}
ax.open("GET",strURL, true);
ax.send(null);
}
</script>
<?php
$sql= mysqli_query($con,"select * from company GROUP BY name ");
//print_r($sql);
?>
<select>
<option value="0">select company name</option>
<?php while ( $row = mysqli_fetch_array($sql))
{
?>
<option onclick="test('<?php echo $row["name"]; ?>');" id="<?php echo $i++."der" ;?>"> <?php echo $row["name"]; ?></option>
<?php }
?>
</select>
<div id="myid"></div>
Now Create a new file f1.php where you can run another mysql query to send the name of company you have selected by test function.here is the code
<?php
$con = mysqli_connect("localhost","root","root","search");
if(isset($_GET['name']))
{
$name = $_GET['name'];
}
$sql= mysqli_query($con,"select * from company where name='$name'");
?>
<select name="city">
<option>Select location</option>
<?php while ($row = mysqli_fetch_array($sql))
{ ?>
<option value=<?php echo $row['location']?>><?php echo $row['location']?></option>
<?php } ?>
</select>

php code to take values from two forms and insert it in table

I have two forms on one page. First one take names of students according to group. Second form is used to enter marks individually. Now i want to insert their marks but failed to do this. Kindly help me regarding this. My code is:
$faculty = null; //declare vars
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Not connected : ' . mysql_error());
}
mysql_select_db('Sims', $link) or die("cannot select DB");
if(isset($_POST["faculty"]))
{
$faculty = $_POST["faculty"];
}
?>
<script language="JavaScript">
function autoSubmit()
{
var formObject = document.forms['theForm'];
formObject.submit();
}
</script>
<form name="theForm" method="post">
<select name="faculty" onChange="autoSubmit();">
<option value="null"></option>
<option value="computer" <?php if($faculty == 'computer') echo " selected"; ?>>Computer</option>
<option value="commerce" <?php if($faculty == 'commerce') echo " selected"; ?>>Commerce</option>
</select>
<br><br>
<?php
if($faculty =='computer')
{
echo "<select name=\"name\">";
$sql = mysql_query("SELECT name FROM std_reg where faculty= 'computer' ") or die(mysql_error());
while($row = mysql_fetch_array($sql)){
echo "<option>".$row[name]."</option>";}
echo "</select>";
}
if($faculty =='commerce')
{
echo "<select name=\"name\">";
$sql = mysql_query("SELECT name FROM std_reg where faculty= 'commerce' ") or die(mysql_error());
while($row = mysql_fetch_array($sql)){
echo "<option>".$row[name]."</option>";}
echo "</select>";
}
?>
<br><br>
</form>
<form method="post">
math <input type="text" name="urdu" />
science <input type="text" name="science" />
social <input type="text" name="social" />
submit
</form>

populate dependent drop down list from database

I want to populate WILAYA dropList after a value is selected on MIKOA drop list. Here is what i did so far. But the drop down list is not populated onChange Event. what ım ı doıng wrong so far?
on first.php
<head>
<script type = "text/javascript">
function jazaWilaya (mkoa_value)
{
var xmlhttp = new XHMLHttpRequest ();
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("wilaya").innerHTML= xmlhttp.reponseText;
}
};
xmlhttp.open ("GET", "wilaya.php?mkoa="+mkoa_value, true);
xmlhttp.send ();
}
</script>
</head>
Inside the same file, here are the 2 drop down lists MKOA & WILAYA
Mkoa:
<select id="mkoa" name ="mkoa" onchange="jazaWilaya(this.value);" >
<option value = "chagua">Chagua</option>
<option>Arusha </option>
<option value = "dsm">Dar-es-Salaam</option>
<option value = "dodoma">Dodoma</option>
<option value = "kagera">Kagera </option>
<option value = "manyara">Manyara</option>
<option value = "mbeya">Mbeya</option>
<option value = "morogoro">Morogoro</option>
<option value = "mwanza">Mwanza</option>
<option value = "mtwara ">Mtwara</option>
<option value = "pwani">Pwani</option>
<option value = "shinyanga">Shinyanga </option>
<option value = "tabora">Tabora</option>
<option value = "tanga">Tanga</option>
<option value = "zanzibar">Zanzibar</option>
</select>
<br><br>
Wilaya:
<select id="wilaya" name="wilaya">
<option>Chagua</option>
<?php
while ($row = mysql_fetch_array($result))
{
?>
<option value = "<?=$row['wilaya_id']?>"><?php echo $row['wilaya_jina'];?></option>
<?php
}
?>
</select>
And this is the query code in another php file called wilaya.php
<?php
// put your code here
$con = mysql_connect("localhost", "root", "root");
if (!$con)
{
echo mysql_error();
}
$mkoa = mysql_real_escape_string($_REQUEST["mkoa"]);
mysql_select_db("dalaliOnline", $con);
$sql = "SELECT wilaya_jina FROM WILAYA WHERE mkoa_jina ='$mkoa' ";
$result =mysql_query($sql, $con);
?>
Correct your code in wilaya.php:
<?php
// put your code here
$con = mysql_connect("localhost", "root", "root");
if (!$con)
{
echo mysql_error();
}
$mkoa = mysql_real_escape_string($_REQUEST["mkoa"]);
mysql_select_db("dalaliOnline", $con);
$sql = "SELECT wilaya_jina FROM WILAYA WHERE mkoa_jina ='$mkoa' ";
$result =mysql_query($sql, $con);
while ($row = mysql_fetch_array($result))
{
?>
<option value = "<?=$row['wilaya_id']?>"><?php echo $row['wilaya_jina'];?></option>
<?php
}
?>
And remove following code from first.php file :
Wilaya: Should be
<select id="wilaya" name="wilaya">
<option>Chagua</option>
</select>
Instead of Wilaya:
<select id="wilaya" name="wilaya">
<option>Chagua</option>
<?php
while ($row = mysql_fetch_array($result))
{
?>
<option value = "<?=$row['wilaya_id']?>"><?php echo $row['wilaya_jina'];?></option>
<?php
}
?>
</select>
I am giving u one more example of a state and city when the user choose one state from the first select box than the 2nd select box appear with its corresponding city try this.
here is the state.php page.
<?php
mysql_connect("localhost","root","");
mysql_select_db("statename");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function showdetails(str)
{
var xmlhttp;
if (str==0)
{
alert("please select state name");
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("showresult").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","details.php?id="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
SELECT STATE:
:<select name="sid" id="sid" onchange="showdetails(this.value)">
<option value="0">Select State Name</option>
<?php
$sql="select sid,statename from state";
$qry=mysql_query($sql);
$num=mysql_num_rows($qry);
if($num>0)
{
while($res=mysql_fetch_array($qry))
{
?>
<option value="<?php echo $res['sid'];?>"><?php echo $res["statename"];?></option>
<?php
}
}
?>
</select>
CITY NAMES:
<div id=showresult></div>
</form>
</body>
</html>
The details.php page
mysql_connect("localhost","root","");
mysql_select_db("statename");
$id = $_REQUEST["id"];
$sql="select * from city where sid='$id'";
$qry=mysql_query($sql);
$num=mysql_num_rows($qry);
?>
<select name="cid" id="cid">
<option value="0">Select City Name</option>
<?php
if($num>0)
{
while($res=mysql_fetch_array($qry))
{
?>
<option value="<?php echo $res['cid'];?>"><?php echo $res["cityname"];?></option>
<?php
}
}
?>
</select>
Here is 2 tables here one is city table(cid, sid, cityname) another is state table(sid, state name) state table's sid is foreign key at sid city table
Following some updates to the question, here is my new answer. Original answer below is not relevant.
Your JavaScript can't do anything unless it has some output from your script to work with. A PHP variable is of no use to it. One solution would be to have wilaya.php create the new options for the select box using your original code for that:
<?php
$con = mysql_connect("localhost", "root", "root");
if (!$con)
{
// we don't want to output anything if something goes wrong, it'll mess the select up
die();
}
$mkoa = mysql_real_escape_string($_REQUEST["mkoa"]);
mysql_select_db("dalaliOnline", $con);
$sql = "SELECT wilaya_jina FROM WILAYA WHERE mkoa_jina ='$mkoa' ";
$result = mysql_query($sql, $con);
?>
<option>Chagua</option>
<?php
while ($row = mysql_fetch_array($result))
{
?>
<option value = "<?php echo $row['wilaya_id']; ?>"><?php echo $row['wilaya_jina']; ?></option>
<?php
}
?>
Then your JavaScript replaces the select box contents with the output of wilaya.php.
You're sending the data as a GET request but you have an if statement checking for a POST variable in wilaya.php, so if (isset ($_POST["mkoa"])) is evaluating to false and nothing is running in that file. Obviously without details of your database I don't know whether this is going to work when you fix that but seems to me that's the place to start. So you'll need to use GET instead of POST to check that this is set, eg:
if (isset ($_GET["mkoa"]))
{
// the rest of your code
}
(I assume below that code you have some output that the JS is using.)
Also, obligatory - the mysql_ extension is deprecated. Update to PDO or mysqli when convenient.
your wilaya.php should look like:
<?php
// put your code here
$con = mysql_connect("localhost", "root", "root");
if (!$con)
{
echo mysql_error();
}
$mkoa = mysql_real_escape_string($_REQUEST["mkoa"]);
mysql_select_db("dalaliOnline", $con);
$sql = "SELECT wilaya_jina FROM WILAYA WHERE mkoa_jina ='$mkoa' ";
$result =mysql_query($sql, $con);
?>
<option>Chagua</option>
<?php
while ($row = mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['wilaya_id']?>"><?php echo $row['wilaya_jina'];?></option>
<?php
}
?>
in your first.php file change
Wilaya:
<select id="wilaya" name="wilaya">
<option>Chagua</option>
</select>

Using Ajax, jQuery and PHP in two dropdown lists

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.)

Categories