change of drop down in php my sql Dynamically - php

I have two drop downs .one have static value and second get values from db. I want to that if value is selected from 1st drop down then relevant values loaded in 2nd drop down. I have tried. but its load all the data from database according to user.for example when user select from request type dropdown having value inquiry.then 2nd drop down load only the values which have catType Inquiry.and if he select the complaint then complaint data must be shown.I have been tried but all the data is loaded ,or only one data is loading.any body help me in this regard.Thanks in Advance. Here is My Code
<div class="col-md-4">
<div class="form-group">
<label for="requesttype"><?php echo $requestField; ?></label>
<select class="form-control" required="" id="requesttype" name="requesttype" onchange="fcrActionChange(this);">
<option value="">Select Request Type</option>
<option value="Inquiry">Inquiry</option>
<option value="Complaint">Complaint</option>
<option value="Service Request/FCR">Service Request/FCR</option>
<option value="Verification Call">Verification Call</option>
</select>
<span class="help-block"><?php echo $requestHelp; ?></span>
</div>
</div>
$("#requesttype").change(function() {
$("#catId).load("navigation.php?requesttype=" + $("#requesttype").val());
});
</script>
<div class="col-md-4">
<div class="form-group">
<label for="catId"><?php echo $categoryField; ?></label>
<select class="form-control" name="catId" id="catId">
$tcat = "SELECT catId, catName FROM categories WHERE userId = ".$userId." AND isActive = 1 AND catType = ".$_GET['requesttype'];
$rest = mysqli_query($mysqli, $tcat) or die('-2'.mysqli_error());
while ($tcatrow = mysqli_fetch_assoc($rest)) {
echo "<option value="$tcatrow['catId'] >";
echo clean($tcatrow['catName'])."</option>";
}
</select>
<span class="help-block"><?php echo $categoryHelp; ?></span>
</div>
</div>
</div>

Your code is pretty confusing but anyway, the important part is within your ajax request and your PHP file
Ex. you have a div id secondOpt to be filled from the query made by the requesttype.
**Note I added a userId input field to pass the value for the SQL query in the navigation.php
<select class="form-control" required="" id="requesttype" name="requesttype" onchange="fcrActionChange(this);">
<option value="">Select Request Type</option>
<option value="Inquiry">Inquiry</option>
<option value="Complaint">Complaint</option>
<option value="Service Request/FCR">Service Request/FCR</option>
<option value="Verification Call">Verification Call</option>
</select>
<input type="hidden" id="userId" value="<?php echo $userId;?>">
<div id="secondOpt"></div>
After this, you will have an ajax request below, you can use $.post from jQuery and render the returned data on the secondOpt element
$('#requesttype').change(function(){
$.post("navigation.php",{requesttype: $(this).val(),userId: $('#userId').val()},function(options)
{
$('#secondOpt').html(options);
});
});
And for the navigation.php UPDATED
//don't forget your config file here to connect with the database
$userId = mysql_real_escape_string($_POST['userId']);
$requesttype = mysql_real_escape_string($_POST['requesttype']);
$output = "<select id='catId'>";
$tcat = "SELECT catId, catName FROM categories WHERE userId = ".$userId." AND isActive = 1 AND catType = ".$requesttype;
$rest = mysqli_query($mysqli, $tcat) or die('-2'.mysqli_error());
while ($tcatrow = mysqli_fetch_assoc($rest)) {
$output.="<option value=".$tcatrow['catId']." >";
$output.=clean($tcatrow['catName'])."</option>";
}
$output.="</select>";
echo $output;

Related

States list drop down is giving first value even after selecting any value from the list upon form submission

Below is my complete code to populate states list based on selected country. When I select any country from country drop down, it returns proper states list in states drop down. This part is working fine.
When I select country USA, states drop down is filled with states of USA and default selected state is Alska. Now if I change state value from Alaska to 'Texas' and submits form, it just sends value 0 to submit page.
I think this 0 value is coming from <option value="0">-- Select State --</option> in id=before_get_state. So how can I resolve this issue? Please help.
Country Drop Down
GetRecordSet is used to fetch records from MySQL database
CheckSelected is used to display specific value as default selected value in dropdown
<form name="frm_shipping_address" id="frm_shipping_address" novalidate>
<div class="control-group form-group">
<div class="controls">
<label>Select Country</label><span class="text-help-form"> * </span>
<?php
$str_query_select="";
$str_query_select="SELECT * FROM " .$STR_DB_TABLE_NAME_COUNTRY. " WHERE visible='YES' ORDER BY title ASC";
$rs_list_country=GetRecordSet($str_query_select);
?>
<select name="cbo_country" id="cbo_country" class="form-control" onChange="get_state(this.value);" required="" data-validation-required-message="Select Country" >
<option value="0">-- Select Country --</option>
<?php
while(!$rs_list_country->EOF()==true) { ?>
<option value="<?php print($rs_list_country->fields("pkid"))?>" <?php print(CheckSelected($rs_list_country->fields("pkid"),$int_user_countrypkid)); ?>><?php print($rs_list_country->fields("title")); ?></option>
<?php $rs_list_country->MoveNext(); } ?>
</select>
</div>
</div>
<button id="btn_continue" class="btn btn-primary btn-lg btn-block"><b>SUBMIT </b></button>
</form>
State Drop Down
<div class="control-group form-group">
<div class="controls">
<label>Select State</label><span class="text-help-form"> * </span>
<div id="before_get_state">
<select name="cbo_state" id="cbo_state" class="form-control">
<option value="0">-- Select State --</option>
</select>
</div>
<div id="after_get_state"></div>
</div>
</div>
jQuery / AJAX
jquery.min.js, jqBootstrapValidation.js files are included in the page
<script>
function get_state(countrypkid) {
var int_countrypkid = countrypkid;
var dataString = "countrypkid="+int_countrypkid;
$.ajax({
type: "POST",
url: "./product_address_get_state_p.php",
data: dataString,
success: function(html)
{
$("#before_get_state").hide();
$("#after_get_state").html(html);
}
});
}
</script>
product_address_get_state_p.php Page Code
$int_statepkid = 0;
if(isset($_SESSION['userpkid']) && $_SESSION['userpkid'] != "")
{
$str_query_select = "SELECT statepkid FROM t_user WHERE pkid=".$_SESSION['userpkid'];
$rs_list_user = GetRecordSet($str_query_select);
$int_statepkid = $rs_list_user->fields("statepkid");
}
$int_countrypkid = 0;
if(isset($_POST["countrypkid"]))
{
$int_countrypkid = trim($_POST["countrypkid"]);
}
$str_query_select = "SELECT * FROM " .$STR_DB_TABLE_NAME_STATE. " WHERE masterpkid=".$int_countrypkid." AND visible='YES' ORDER BY title ASC";
$rs_list_state = GetRecordSet($str_query_select);
echo "<select class='form-control' name='cbo_state' id='cbo_state'>";
while(!$rs_list_state->EOF()==true)
{
echo "<option value='" .$rs_list_state->fields('pkid'). "' ".CheckSelected($rs_list_state->fields('pkid'),$int_statepkid).">".$rs_list_state->fields('title')."</option>";
$rs_list_state->MoveNext();
}
echo "</select>";

Setting a select option default to a previously set option

In my modal window, I have a select where a user can select a breakfast meal from my database. By selecting a meal and submitting it, a record is saved in the database. However, I would like to achieve that when the user enters into the same modal window, whatever meal they have selected before hand will appear as the default option. I have created a query that checks to see if a meal has already been selected (optionquery1). Any ideas to achieve this? Thanks
On a side note, I'm not sure that I'm setting the date php variable currently. The day, month and year is stored in the html hidden inputs but not sure how to extract the values.
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<div class="modal-body">
<form action="my_planner.php" method="post">
<!--<span class="test5"></span>-->
<!--<span class="test"><input type="text" name="id_disabled" value="" disabled/>-->
<input class="test" type="text" name="id1" value="" style="text-align:center; border:0px; font-weight:bold; font-size: 25px;"/>
<hr class="my-4">
<input type="hidden" name="id" value=""/>
<input type="hidden" name="month" value=""/>
<input type="hidden" name="year" value=""/>
<br>
<p id="breakfastTag"><br>Breakfast:</p>
<select id="breakfast" name="breakfast">
<option value="" disabled selected>Select your breakast</option>
<?
$meal='breakfast';
$date='<input type="hidden" name="id" value=""/>'.'<input type="hidden" name="month" value=""/>'.'<input type="hidden" name="year" value=""/>';
$query = $db->prepare("select * from recipe_category where categoryID=1");
$query->execute();
while ($results = $query->fetch()) {
$recipeID=$results["recipeID"];
$query3 = $db->prepare("select * from recipe where id=:recipeID");
$dbParams3=array('recipeID'=>$recipeID);
$query3->execute($dbParams3);
$breakfast = $query3->fetchAll();
$optionquery = $db->prepare("select * from user_planner where userID=:userID and date=:date and meal=:meal");
$optionParams= array ('userID'=>$thisUser, 'date'=>$date,'meal'=>$meal);
$optionquery->execute($optionParams);
while ($results12 = $optionquery->fetch()) {
$selectedmeal = $results12['recipeID'];
}
$optionquery1 = $db->prepare("select * from recipe where id=:recipeID");
$optionParams1= array ('recipeID'=>$selectedmeal);
$optionquery1->execute($optionParams1);
while ($results123 = $optionquery1->fetch()) {
$selectedrecipe = $results123['name'];
}
foreach($breakfast as $breakfast): ?>
<option value="<?= $breakfast['id']; ?>"><?= $breakfast['name']; ?></option>
<?php endforeach;} ?>
</select>
Of course you can, you need to use the selected attribute on the <option> you want to show.
First remove the selected attribute from the first <option>:
<option value="" disabled>Select your breakast</option>
Then in the foreach loop you need an if condition:
$results123 = $optionquery1->fetch();
$selectedrecipe = $results123['id'];
foreach($breakfast as $breakfast): ?>
<option value="<?= $breakfast['id']; ?>" <?php if ($breakfast['id'] == $selectedrecipe) echo 'selected' ?>><?= $breakfast['name']; ?></option>
<?php endforeach;} ?>
Notice I have removed the while loop since we are sure Mysql will return only one record (WHERE ID = <ID>).

sending data rows to combo box

First of all this one its just a part of my code, what I'm trying to do here is to send data from DB to html input by clicking a button, other text-input is doing good but in my combo-box I got the problem of not showing anything, I tried to use the same way of other input(add the echo inside the value) its not working on with me, any ideas ??
The code is working without any ERROR
<?php
$query10s = "select payement.ID_PAYEMENT,DATE_PAYEMENT,TYPE_DE_PAYEMENT,PRIX,MOIS_PAYEMENT from eleve,payement,payer where eleve.CIN_ELEVE = payer.CIN_ELEVE and payement.ID_PAYEMENT = payer.ID_PAYEMENT and eleve.CIN_ELEVE = '$InputCIN' group by payement.ID_PAYEMENT";
$resultAf10 = mysqli_query($con,$query10s);
if(mysqli_num_rows($resultAf10)>=0){
while($rows = mysqli_fetch_assoc($resultAf10)){
$ID_PAYEMENT = $rows['ID_PAYEMENT'];
$DATE_PAYEMENT = $rows['DATE_PAYEMENT'];
$TYPE_DE_PAYEMENT = $rows['TYPE_DE_PAYEMENT'];
$PRIX = $rows['PRIX'];
$MOIS_PAYEMENT = $rows['MOIS_PAYEMENT'];
}
}
ID PAYEMENT<input type='text' name='ID_PAYEMENT' class="form-control" value="<?php if(isset($ID_PAYEMENT)){echo $ID_PAYEMENT;}?>">
<div style="font-size:9px;display:none;" class="col-md-12 showAj1">
DATE PAYEMENT<input type='text' name='DATE_PAYEMENT' class="form-control date" value="<?php if(isset($DATE_PAYEMENT)){echo $DATE_PAYEMENT;}?>">
TYPE DE PAYEMENT<br>
<select class='form-control' style="font-size:11px;" name="TYPE_DE_PAYEMENT" value="<?php if(isset($TYPE_DE_PAYEMENT)){echo $TYPE_DE_PAYEMENT;}?>">
<option>Mentuel</option>
<option>Frais inscription</option>
<option>Droit examen</option>
</select>
PRIX<input type='text' name='PRIX' class="form-control col-md-12" value="<?php if(isset($PRIX)){echo $PRIX;}?>"><span style="margin-left:280px;margin-top:-22px;position:absolute;font-size:10px;">DH</span>
MOIS_PAYEMENT<select class="form-control" style="font-size:11px;" name="MOIS_PAYEMENT" value="<?php if(isset($MOIS_PAYEMENT)){echo $MOIS_PAYEMENT;}?>">
<option>Janvier</option>
<option>Février </option>
<option>Mars</option>
<option>Avril </option>
<option>Mai </option>
<option>Juin</option>
<option>Juillet </option>
<option>Août </option>
<option>Septembre </option>
<option>Octobre </option>
<option>Novembre</option>
<option>Décembre</option>
</select><br>
?>

Empty query result

in a web form there are two drop-down lists. The second list items should change dynamically depending on the value selected on the first drop-down list.
This is how am I trying to do it:
index.php:
...
<script>
function getClient(val) {
$.ajax({
type: "POST",
url: "get_contacts.php",
data:'client_id='+val,
success: function(data){
$("#contacts-list").html(data);
}
});
}
</script>
...
<div class="form-group">
<label for="mto_client" class="col-sm-2 control-label">MTO Client</label>
<div class="col-sm-10">
<select name="mto_client" id="clients_list" onChange="getClient(this.value)">
<option value="">Select a Client</option>
<?php
do {
?>
<option value="<?php echo $row_RSClients['id_client']?>" ><?php echo $row_RSClients['client_name']?></option>
<?php
} while ($row_RSClients = mysql_fetch_assoc($RSClients));
?>
</select>
</div>
</div>
<div class="form-group">
<label for="mto_client_contact" class="col-sm-2 control-label">MTO Client Contact</label>
<div class="col-sm-10">
<select name="state" id="contacts-list">
<option value="">Select Client Contact</option>
</select>
</div>
</div>
get_contacts.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["client_id"])) {
$query ="SELECT * FROM tb_client_contacts WHERE contact_client_id = '" . $_POST["client_id"] . "'";
$results = $db_handle->runQuery($query);
?>
<option value="">Select Client Contact</option>
<?php
foreach($results as $state) {
?>
<option value="<?php echo $state["id_client_contact"]; ?>"><?php echo $state["contact_name"]; ?></option>
<?php
}
}
?>
There are objects on the table tb_clients_contact that meet the condition, but the second drop-down list doesn't show any objects.
Any help is welcome.
Instead of
$("#contacts-list").html(data);
It should be
$('#contacts-list').empty().append(data);
empty() will clear first the options inside the contacts-list select field, then append() will insert the options from the result of your AJAX.
You can also look at the console log for errors. If you are using Google Chrome, hit F12 to display the console log.

Show/hide select values based on previous select choice

I have 2 select's inside a form. The second select has about 2000 lines in total coming out of my mysql table. One of the column into that mysql has 1 of the values used into the first select. I want to be able to filter on that value when it is selected into the first select, so that it only shows these articles.
code now:
<div class="rmaform">
<select name="discipline" class="discipline">
<option value=" " selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article">
<?php
$articleselect = $dbh->prepare('SELECT * FROM articles');
$articleselect->execute();
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
</select>
I think i have to use Javascript for it but how do you combine PHP and Javascript? And what would be the best way to make the filter work?
jQuery for the change event and AJAX
$(document).ready(function(e) {
$('select.discipline').change(function(e) { // When the select is changed
var sel_value=$(this).val(); // Get the chosen value
$.ajax(
{
type: "POST",
url: "ajax.php", // The new PHP page which will get the option value, process it and return the possible options for second select
data: {selected_option: sel_value}, // Send the slected option to the PHP page
dataType:"HTML",
success: function(data)
{
$('select.input-article').append(data); // Append the possible values to the second select
}
});
});
});
In your AJAX.php
<?php
if(isset($_POST['selected_option']))
$selected_option=filter_input(INPUT_POST, "selected_option", FILTER_SANITIZE_STRING);
else exit(); // No value is sent
$query="SELECT * FROM articles WHERE discipline='$selected_option'"; // Just an example. Build the query as per your logic
// Process your query
$options="";
while($query->fetch()) // For simplicity. Proceed with your PDO
{
$options.="<option value='option_value'>Text for the Option</option>"; // Where option_value will be the value for you option and Text for the Option is the text displayed for the particular option
}
echo $options;
?>
Note: You can also use JSON instead of HTML for much simplicity. Read here, how to.
First give both of the selects an unique ids...
<div class="rmaform">
<select name="discipline" class="discipline" id="discipline">
<option value="" selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article" id="article">
<option value="" selected></option>
</select>
Now you can use jQuery Ajax call to another file and get the HTML Response from that file and Populate in the select field with id="article" like this...
<script type="text/javascript">
$(document).ready(function(){
$("#discipline").change(function(){
var discipline = $(this).val();
$.post(
"ajax_load_articles.php",
{discipline : discipline},
function(data){
$("#article").html(data);
}
)
});
});
</script>
Now create a new file like ajax_load_articles.php... in the same directory where the html file exists... You can place it anywhere but then you have to change the $.post("url", the url to the ajax submission.
Contents of ajax_load_articles.php :
<?php
$discipline = $_POST["discipline"];
$articleselect = $dbh->prepare("SELECT * FROM articles WHERE colname = '{$discipline}'");
$articleselect->execute();
echo '<option value="" selected></option>';
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
Now when ever you will change the select of the first select field an Ajax call will take place and the data of the second select field will automatically adjust to related data selected in the first select field.
This is an example where you can select the college specific to the state ..
Form.php
// your code for form ...
// select box for state starts
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">State</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="statename" id="stateid">
<option value="">---- Select ----</option>
<?php
$state=sql::readResultArray("Your Query To select State`");
foreach($state as $s){
?>
<option value="<?php echo $s?>"> <?php echo $s ?> </option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">Colleges</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="mycollegename">
<option value="">--- Select --- </option>
</select>
</div>
</div>
// further code for from in form.php..
Script to find the state and then pass the value to find the respective colleges in that state
<script>
$(document).ready(function(e) {
$('#stateid').change(function()
{ ids=$('#stateid').val();
$.get('mycollege.php', {type:ids} ,function(msg){
$('select[name="mycollegename"]').html(msg);
});
});
});
</script>
Call this file through ajax .. Code on this file
mycollege.php
<?php
require('db.php'); // call all function required, db files or any crud files
$type=$_GET['type'];
if(!empty($type)){
$r=sql::read("Your Query To call all teh college list");
?>
<select name="mycollegename">
<option value="">Select One</option>
<?php
foreach($r as $r){
echo "<option value=\"$r->collegename\">$r->collegename </option>";
}
?>
</select>
<?php }else{ ?>
<select name="mycollegename">
<option value="">Select State</option>
</select>
<?php } ?>

Categories