PHP/JS: Dynamic Dropboxes and echoing SELECTED value - php

I am currently working with a dynamic dropdown menu(dependable select boxes). I am pulling the values straight from MySQL DB(if your curious here is how i have the DB SETUP). I am able to get the values of each table and display them accordingly. The problem I am having is echoing the SELECTED value of each selct box. I have a created JS function that will request postfile.php which will then echo the SELECTED value of each box. I am not getting anything echoed. I have checked with firebug but nothing is being posted.
How can I make this work? or Am I approaching this wrong? or Is there a better way? EXAMPLE
Working HTML/PHP
<?php
include ('includes/dbConnect.php');
try {
$pdo = get_database_connection();
$sql = "SELECT *
FROM `categories`
WHERE `master_id` = 0";
$statement = $pdo->query($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'There was a problem';
}
?>
<select name="main" id="main" size="7" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="subc1" id="subc1" size="7" class="update" disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
<select name="subc2" id="subc2" size="7" class="update" disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
<select name="subc3" id="subc3" size="7" class="update" disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
JS
<script type="text/javascript">
$(document).ready(function () {
$('#main).change(function() {
if ($(this).val()!='
') {
$("#subc1").load("postfile.php",{main_id: $(this).val()});
//$("#subc1").removeAttr('
disabled hidden ');
}
});
//code on change of sel_source
$('#subc1 ').change(function() {
if ($(this).val()!='
') {
$("#subc2").load("postfile.php",{subc1_id: $(this).val()});
//$("#colour").removeAttr('
disabled ');
}
});
$('#subc2 ').change(function() {
if ($(this).val()!='
') {
$("#subc3").load("postfile.php",{subc2_id: $(this).val()});
//$("#colour").removeAttr('
disabled ');
}
});
});
</script>
PHP- postfile.php
if(isset($_REQUEST['main_id']) && !empty($_REQUEST['main_id'])) {
try {
include ('../includes/dbConnect.php');
$pdo = get_database_connection();
$sql = ("select * from `categories` where id='".$_REQUEST['main_id']."' ");
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
}catch(PDOException $e) {
echo 'There was a problem';
}
if($number_of_rows > 0) {
$output = '<option value="">Select</option>';
while($row = mysql_fetch_assoc($result)) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}
if(isset($_REQUEST['subc1_id']) && !empty($_REQUEST['subc1_id'])) {
$result = mysql_query("select * from table where id='".$_REQUEST['subc1_id']."' ");
if($number_of_rows > 0) {
$output = '<option value="">Select</option>';
while($row = mysql_fetch_assoc($result)) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}
if(isset($_REQUEST['subc2_id']) && !empty($_REQUEST['subc2_id'])) {
$result = mysql_query("select * from table where id='".$_REQUEST['subc2_id']."' ");
if($number_of_rows > 0) {
$output = '<option value="">Select</option>';
while($row = mysql_fetch_assoc($result)) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}

Maybe you would like to use jQuery UI auto-complete. It is easier to use and less code. It has a remote data source also. Try this one, maybe this can solve your problem. http://jqueryui.com/demos/autocomplete/

Add on submit action to the form. In the function use the following:
var Myvar = $('#subc3 :selected').text();

Related

Dependent Dropdown list

I am newbie to JQuery Ajax. May i know how to create a PHP to read the subcategory list depends on the selected maincategory? So far i had create a jQuery AJAX in my asset_add.php
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#main_category').on('change',function(){
var categoryNAME = $(this).val();
if(categoryNAME){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'ac_maincategory='+categoryNAME,
success:function(html){
$('#sub_category').html(html);
}
});
}else{
$('#sub_category').html('<option value="">Select main category first</option>');
}
});
});
</script>
and for HTML,
<tr>
<td valign=top><strong>MAIN CATEGORY</td>
<td><select name="main_category" id="main_category" onchange="this.form.submit()" required>
<?php
$sql = "SELECT * FROM asset_category GROUP BY ac_maincategory" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
?>
<option value=""></option>
<?php
if($count > 0)
{
while ($rs = mysqli_fetch_array($result))
{
$ac_maincategory = $rs["ac_maincategory"];
$ac_id = $rs["ac_id"];
?>
<option value="<?=$ac_id?>"><?=$ac_maincategory?></option>
<?php
}
}
?>
</select>
</td>
</tr>
<tr>
<td valign=top><strong>SUB CATEGORY</td>
<td><select id= "sub_category" name="sub_category" autocomplete="off"/ required>
<option value=""></option>
</select>
</tr>
while in my ajaxData.php
<?php
//Include database configuration file
require("config.php");
$conn = dbconnect();
if(isset($_POST["ac_maincategory"]) && !empty($_POST["ac_maincategory"]))
{
$sql = "SELECT * FROM asset_category WHERE ac_maincategory = ".$_POST['ac_maincategory']."" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
if($count > 0)
{
echo '<option value="">Select Subcategory</option>';
while ($rs = mysqli_fetch_array($result))
{
$ac_subcategory = $rs["ac_subcategory"];
$ac_id = $rs["ac_id"];
echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
}
}
}
?>
However, when i choose a maincategory in asset_add.php, nothing shown in subcategory. Can anyone tell me which part i do wrong? Thanks for help
Seems you are replacing whole div with $('#sub_category').html(html); so there is only options printed on the view
You can solve it by replacing the line
$('#sub_category').html(html);
to
$('#sub_category').append(html);
Or Just replace this code in ajaxData.php , S
//Include database configuration file
require("config.php");
$conn = dbconnect();
if(empty($_POST["ac_maincategory"])){
die("category is empty");
}
$sql = "SELECT * FROM asset_category WHERE ac_maincategory = " . $_POST['ac_maincategory'];
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if($count > 0)
{
echo '<select id= "sub_category" name="sub_category" autocomplete="off"/ required>';
echo '<option value="">Select Subcategory</option>';
while ($rs = mysqli_fetch_array($result))
{
$ac_subcategory = $rs["ac_subcategory"];
$ac_id = $rs["ac_id"];
echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
}
echo "</select>";
}
this is simple question and should be fixed ASAP. but idk why still not solved yet.
so, please try this
html
remove onchange attribute (remove native js event trigger style with jquery style)
optional:
fix several unclosed tag html
remove unrecomended PHP writing style
into this
<tr>
<td valign="top"><strong>MAIN CATEGORY</strong></td>
<td>
<select name="main_category" id="main_category" required>
<option value=""></option>
<?php
$sql = "SELECT * FROM asset_category GROUP BY ac_maincategory" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
if($count > 0)
{
while ($rs = mysqli_fetch_array($result))
{
echo '<option value="'. $rs["ac_id"] .'">'.$rs["ac_maincategory"].'</option>';
}
}
?>
</select>
</td>
</tr>
<tr>
<td valign="top"><strong>SUB CATEGORY</strong></td>
<td>
<select id= "sub_category" name="sub_category" autocomplete="off" required>
<option value="">Select main category first</option>
</select>
</td>
</tr>
jquery
change on('change') with change() // possible dont know when to use on or not
change wrong comparasion on categoryNAME
optional:
change serialize data style using data {} //better for newbie to study
into this
<script>
$(function(){
$('#main-category').change(, function(){
var categoryNAME = $(this).val();
if(categoryNAME != ''){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:{ac_maincategory: categoryNAME},
success:function(html){
$('#sub_category').html(html);
}
});
}else{
$('#sub_category').html('<option value="">Select main category first</option>');
}
})
});
</script>
PHP
reposition default sub-category value out of $count comparasion
into this
<?php
//Include database configuration file
require("config.php");
$conn = dbconnect();
if(isset($_POST["ac_maincategory"]) && !empty($_POST["ac_maincategory"]))
{
$sql = "SELECT * FROM asset_category WHERE ac_maincategory = ".$_POST['ac_maincategory']."" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
echo '<option value="">Select Subcategory</option>';
if($count > 0)
{
while ($rs = mysqli_fetch_array($result))
{
$ac_subcategory = $rs["ac_subcategory"];
$ac_id = $rs["ac_id"];
echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
}
}
}
?>
<?php
//.....
//you sql......$result
//.....
if($_POST['ac_maincategory']) {
//this is test
if($_POST['ac_maincategory']=="aaa"){
$result=array("k1"=>"v1","k2"=>"v2");
}else{
$result=array("kk1"=>"v11","kk2"=>"v22");
}
$str = '<option value="">Select Subcategory</option>';
foreach ($result as $k => $v) {
$str .= '<option value="' . $k . '">' . $v . '</option>';
}
echo $str;exit;
}
?>
<html>
<head></head>
<body>
<div>
<select id="main_category">
<option value=""></option>
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
</select>
</div>
<div>
<select id="sub_category">
<option value=""></option>
</select>
</div>
</body>
</html>
<script src="http://www.w3school.com.cn/jquery/jquery-1.11.1.min.js"></script>
<script>
$("#main_category").change(function () {
var categoryNAME=$(this).val();
$.ajax({
type:'POST',
url:'',
data:{"ac_maincategory":categoryNAME},
success:function(html){
$('#sub_category').html(html);
}
});
})
</script>
test image
https://i.stack.imgur.com/oJLKo.png
https://i.stack.imgur.com/oIw03.png
https://i.stack.imgur.com/vQQrz.png

php use 1 sql statement

How can I make my queries short?
I have the same query multiple times on my page on different sections.
Here's the code to see what I mean:
//sql for dropdown contact type
$sql_getContactType1 = $db->query('SELECT * FROM tb_phone_contact_type');
$sql_getContactType2 = $db->query('SELECT * FROM tb_phone_contact_type');
$sql_getContactType3 = $db->query('SELECT * FROM tb_phone_contact_type');
Output in dropdown:
<select name="contact_type1" class="form-control">
<?php
while($row = $sql_getContactType1->fetch_assoc())
{
echo '<option value="'.$row[id].'">'.$row[d_name] . '</option>';
}
?>
</select>
<select name="contact_type2" class="form-control">
<?php
while($row = $sql_getContactType2->fetch_assoc())
{
echo '<option value="'.$row[id].'">'.$row[d_name] . '</option>';
}
?>
<select name="contact_type3" class="form-control">
<?php
while($row = $sql_getContactType3->fetch_assoc())
{
echo '<option value="'.$row[id].'">'.$row[d_name] . '</option>';
}
?>
</select>
How can I achieve it in just one query statement on my output?
Do the query once, put the results in an array, and then use that array in each <select>.
<?php
$sql_getContactType = $db->query('SELECT id, name FROM tb_phone_contact_type');
$contact_types = array();
while ($row = $sql_getContactType->fetch_assoc()) {
$contact_types[] = $row;
}
?>
<select name="contact_type1" class="form-control">
<?php
foreach($contact_types as $row)
{
echo '<option value="'.$row[id].'">'.$row[d_name] . '</option>';
}
?>
</select>
<select name="contact_type2" class="form-control">
<?php
foreach($contact_types as $row)
{
echo '<option value="'.$row[id].'">'.$row[d_name] . '</option>';
}
?>
<select name="contact_type3" class="form-control">
<?php
foreach($contact_types as $row)
{
echo '<option value="'.$row[id].'">'.$row[d_name] . '</option>';
}
?>
</select>
Why using 3 select? u can use one they do same job.
For selects you must use foreach.
First, get all data in a single query. Then you can add if inside your loop to determine the contact type to show. This example code may help you:
$contacts = $db->query('SELECT * FROM tb_phone_contact_type')->fetch_assoc();
<select name="contact_type1" class="form-control">
<?php
foreach ($contacts as $contact) {
// fit this code by the `type` you want to show
if ($contact['type'] === 'CONTACT_TYPE_1') {
echo '<option value="'.$contact['id'].'">'.$contact['d_name'].'</option>';
}
}
?>
</select>
<select name="contact_type2" class="form-control">
<?php
foreach ($contacts as $contact) {
// fit this code by the `type` you want to show
if ($contact['type'] === 'CONTACT_TYPE_2') {
echo '<option value="'.$contact['id'].'">'.$contact['d_name'].'</option>';
}
}
?>
<select name="contact_type3" class="form-control">
<?php
foreach ($contacts as $contact) {
// fit this code by the `type` you want to show
if ($contact['type'] === 'CONTACT_TYPE_3') {
echo '<option value="'.$contact['id'].'">'.$contact['d_name'].'</option>';
}
}
?>
</select>
Execute query and store data into array... You can use array multiple times..
$sql_getContactType1 = $db->query('SELECT * FROM tb_phone_contact_type');
while($row = $sql_getContactType1->fetch_assoc())
{
$row_info[] = $row;
}
foreach ($row_info as $info) {
echo "Id: {$info[id]}<br />"
. "Name: {$info[name]}<br />"
. "Code: {$info[code]}<br /><br />";
}
SQL for dropdown contact type
<?php
$sql_getContactType1 = $db->query('SELECT * FROM tb_phone_contact_type');
while($row = $sql_getContactType1->fetch_assoc())
{
$row_data[] = $row;
}
?>
Output in dropdown :
<select name="contact_type1" class="form-control">
<?php
foreach($row_data as $row_val)
{
echo '<option value="'.$row_val[id].'">'.$row_val[d_name] . '</option>';
}
?>
</select>
<select name="contact_type2" class="form-control">
<?php
foreach($row_data as $row_val)
{
echo '<option value="'.$row_val[id].'">'.$row_val[d_name] . '</option>';
}
?>
<select name="contact_type3" class="form-control">
<?php
foreach($row_data as $row_val)
{
echo '<option value="'.$row_val[id].'">'.$row_val[d_name] . '</option>';
}
?>
</select>
Use above the code if you need 3 dropdown on a page.

Option selected using ajax and php

I have some dropdown select as below
<div class="dep" style="display: inline;">
<select name="dep" id="dep" class="drp" style="width:19%;">
<option value="">Choose departament</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
$selected = "";
if(isset($_POST['dep'])){
if ($_POST['dep'] == $row['D_id']) {
$selected = "selected='selected'";
}
}
echo '<option value="'.$row["D_id"].'" '.$selected.' >'.$row['Emri'].'</option>';
}
}else{
echo '<option value="">No Departaments</option>';
}
?>
</select>
</div>
The below dropdown filled when i select department using ajax
<div class="dega" style="display: inline;">
<select name="dega" id="dega" class="drp" style="width:19%;">
<option value="">Choose Sector </option>
</select>
</div>
to be filled need the follows :
ajax:
<script type="text/javascript">
$(document).ready(function(){
$('#dep').on('change',function(){
var dep_id = $(this).val();
if(dep_id){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'D_id='+dep_id,
success:function(html){
$('#dega').html(html);
}
});
}else{
$('#dega').html('<option value="">choose departament</option>');
}
});
});
And the ajaxData.php file where the ajax code take the values
include('dbConfig.php');
if(isset($_POST["D_id"]) && !empty($_POST["D_id"])){
$query = $db->query("SELECT * FROM deget WHERE D_id = ".$_POST['D_id']."");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Choose sector</option>';
while($row = $query->fetch_assoc()){
$sel = "";
if (isset($_POST['dega'])) {
if ($_POST['dega'] == $row['Dg_id']) {
$sel = "selected='selected'";
}
}
echo '<option value="'.$row['Dg_id'].'" '.$sel.'>'.$row['Emri'].'</option>';
}
}else{
echo '<option value="">No sectors revalent to department</option>';
}
}
Everything works fine except something.When i post the button all my dropdown are selected because i use selected='selected' EXCEPT the second dropdown choose sector and that because i have used ajax.I have tried on php file that took with ajax to make the option selected but it does not works.Any idea?
i find my problem and the solution is :
<div class="dega" style="display: inline;">
<select name="dega" id="dega" class="drp" style="width:19%;">
<?php if(isset($_POST['kot'])){
//Include database configuration file
include('dbConfig.php');
//Merr te dhenat e degeve perkatese te departamentit te selektuar
$query = $db->query("SELECT * FROM deget WHERE D_id = ".$_POST['dep']."");
//Rreshtat e querit
$rowCount = $query->num_rows;
//Mbush dropdown e degeve
if($rowCount > 0){
echo '<option value="">Zgjidh Degen</option>';
while($row = $query->fetch_assoc()){
$sel = "";
if($_POST['dega'] == $row['Dg_id']){
$sel = "selected='selected'";
}
echo '<option value="'.$row['Dg_id'].'" '.$sel.'>'.$row['Emri'].'</option>';
}
}else{
echo '<option value="">Nuk ka dege perkatese</option>';
}
}else{?>
<option value="">Selekto Degen </option>
<?php }?>
</select>
</div>

keeping selected value in the dropdown after reloading the page in php

I have a dropdown in my form, In which data is being fetch from database, Problem is i want to keep the selected value in the dropdown if page reloads. Any help will be really appreciated.
Here is my code
<select name="ans_type" class="select-form " onChange="checkAnswer(this.value)" style="background-color: #fff !important;width:159px!important;">
<option value="" style="color:#000">Select</option>
<?php
$sql = "select * from (table name)";
$res = mysqli_query($dbhandle,$sql);
$numrows = mysqli_num_rows($res);
if($numrows){
while($obj = mysqli_fetch_object($res)){
if($ansTypeId == $obj->id){
echo '<option value="'.$obj->id.'" style="color:#000" selected>'.($obj->ans_type).'</option>';
}
else{
echo '<option value="'.$obj->id.'" style="color:#000">'.($obj->ans_type).'</option>';
}
}
}
?>
</select>
Try below code.
<select name="ans_type" class="select-form " onChange="checkAnswer(this.value)" style="background-color: #fff !important;width:159px!important;">
<option value="" style="color:#000">Select</option>
<?php
$selectStr = '';
$sql = "select * from (table name)";
$res = mysqli_query($dbhandle,$sql);
$numrows = mysqli_num_rows($res);
if($numrows){
while($obj = mysqli_fetch_object($res)){
$selectStr = ($ansTypeId == $obj->id) ? 'selected' : '';
echo '<option value="'.$obj->id.'" style="color:#000" '.$selectStr.'>'.($obj->ans_type).'</option>';
}
}
?>
</select>
Try this
selected = '';
if($ansTypeId == $obj->id){
$selected = "selected='selected'";
}
echo '<option value="'.$obj->id.'" style="color:#000" $selected>'.
($obj->ans_type).'</option>';

keep the selected value for dropdown after submit

How do I keep the selected item after I submit the page? I have the country dropdown list with the following code.
<?php
$SQL = "SELECT countr_id, country_name FROM countries";
$Result = mysql_query($SQL) or die(mysql_error());
?>
<select name="country" style="width:400px"> <option value='-1'></option>
<?php
while($row = mysql_fetch_array($Result))
{
echo "<option value=\"".$row["country_id"]."\">".$row["country_name"]."</option>";
}
?>
<?php
$SQL = "SELECT countr_id, country_name FROM countries";
$Result = mysql_query($SQL) or die(mysql_error());
?>
<select name="country" style="width:400px"> <option value='-1'></option>
<?php
while($row = mysql_fetch_array($Result))
{
echo "<option value=\"".$row["country_id"]."\"";
if($_POST['country'] == $row['country_id'])
echo 'selected';
echo ">".$row["country_name"]."</option>";
}
?>
<?php
while($row = mysql_fetch_array($Result))
{
if ($_POST['country'] == $row["country_id"]) {
echo "<option value=\"".$row["country_id"]."\" selected="selected">".$row["country_name"]."</option>";
} else {
echo "<option value=\"".$row["country_id"]."\">".$row["country_name"]."</option>";
}
}
?>
<?php
$SQL = "SELECT countr_id, country_name FROM countries";
$Result = mysql_query($SQL) or die(mysql_error());
?>
<select name="country" style="width:400px"> <option value='-1'></option>
<?php
while($row = mysql_fetch_array($Result))
{
echo "<option ";
if($_REQUEST['country'] == $row["country_id"]) echo 'selected="selected" ';
echo "value=\"".$row["country_id"]."\">".$row["country_name"]."</option>";
}
?>
This code depends if you are trying to keep the value after you submit back to the original page.
<?php
$SQL = "SELECT countr_id, country_name FROM countries";
$Result = mysql_query($SQL) or die(mysql_error());
?>
<select name="country" style="width:400px">
<option value='-1'></option>
<?php
while($row = mysql_fetch_array($Result))
{
echo "<option ";
if($_REQUEST["yourSelectName"] ==$row["country_id"])
echo ' selected = "selected" ';
echo " value=\"".$row["country_id"]."\">".$row["country_name"]."</option>";
}
?>
</select>
Or you can do it all inline... less code, doesn't require all the if/then/else stuff
Change
echo "<option value=\"".$row["country_id"]."\">".$row["country_name"]."</option>";
To
echo "<option ". (($_POST['country'] == $row["country_id"]) ? 'selected ' : '') ."value=\"".$row["country_id"]."\">".$row["country_name"]."</option>";
If it is get (passed in URL), the use GET
<?php
$selectedid = 5; //example of selected if before submitting
$SQL = "SELECT countr_id, country_name FROM countries";
$Result = mysql_query($SQL) or die(mysql_error());
?>
<select name="country" style="width:400px"> <option value='-1'></option>
<?php
while($row = mysql_fetch_array($Result))
{
echo "<option value=\"".$row["country_id"]." ".(($selected==$row["country_id"])?"SELECTED":"")."\">".$row["country_name"]."</option>";
}
?>
//assume you have $result = array(your result list);
<select name='question'>
<?php
foreach ($result as $question) {
if ($_POST['question'] == $question) {
$selected = "selected";
} else {
$selected = '';
}
echo "<option value='" . $question . "' $selected>$question</option>";
}
?>
</select>

Categories