I am using dropdown to select values, and after I click the submit button, my values change. Please help me retain the selected values. Using POST method I have got the solution, but I want to use with GET method. Is it possible?
1.) 1st select stmt:
<form action="" method="GET">
<select name="sort" >
<option value="inc_patientName">Patient Name</option>
<option value="inc_date">Date</option>
<option value="inc_status">Status</option>
<option value="inc_patientAge">Age</option>
</select>
<input type="submit" name="GETREPORT" value="Get Report"/>
if ($_GET)
{echo"hi";}
</form>
2.) 2nd select with while
<?php
//Selecting ward from table ward master
$sql = "SELECT ward_name,ward_id FROM ward_master";
$result = mysql_query($sql);
echo "<select name='ward'>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['ward_id'] . "'>" . $row['ward_name'] . "</option>";
}
echo "</select>";
?>
3.) 3rd select with javascript:
<select name="daydropdown" id="daydropdown" ></select>
<select name="monthdropdown" id="monthdropdown"></select>
<select name="yeardropdown" id="yeardropdown"></select>
<script type="text/javascript">
populatedropdown("daydropdown", "monthdropdown", "yeardropdown")
Javascript code:
<script type="text/javascript">
var monthtext=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
function populatedropdown(dayfield, monthfield, yearfield)
{
var today=new Date()
var dayfield=document.getElementById(dayfield)
var monthfield=document.getElementById(monthfield)
var yearfield=document.getElementById(yearfield)
for (var i=1; i<=31; i++)
dayfield.options[i]=new Option(i, i)
dayfield.options[today.getDate()]=new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m=0; m<12; m++)
monthfield.options[m]=new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear=1999
for (var y=0; y<45; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear+=1
}
yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
</script>
try
if(isset($_GET['sort'])) {
echo $_GET['sort'];
}
and get selected index
<option value="inc_patientName" <?php if (isset($_GET['sort']) && $_GET['sort'] == "inc_patientName") echo 'selected="seleceted"'; ?>>Patient Name</option>
and so on for all options values match
For 2nd dropdown:-
while ($row = mysql_fetch_array($result)) {?>
<option value="<?php echo $row['ward_id'];?>" <?php if (isset($_GET['sort']) && $_GET['sort'] == $row['ward_id']) echo 'selected="seleceted"'; ?>><?php echo $row['ward_name'];?></option>
<?php }
use it like this... it myt work.
<select name="ward">
<?php
$sql = "SELECT ward_name,ward_id FROM ward_master";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
if ($_GET['ward']==$row["ward_id"]) {
echo '<option selected="selected" value='.$row["ward_id"].'>'.$row["ward_name"].'</option>';
} else {
echo '<option value='.$row["ward_id"].'>'.$row["ward_name"].'</option>';
}
}
?>
</select>
You can do something like this:
<select name="sort" >
<option value="inc_patientName"<?php if ($_GET['sort'] == 'inc_patientName') echo ' selected="seleceted"'; ?>>Patient Name</option>
<option value="inc_date"<?php if ($_GET['sort'] == 'inc_date') echo ' selected="seleceted"'; ?>>Date</option>
<option value="inc_status" <?php if ($_GET['sort'] == 'inc_status') echo ' selected="seleceted"'; ?>>Status</option>
<option value="inc_patientAge"<?php if ($_GET['sort'] == 'inc_patientAge') echo ' selected="seleceted"'; ?>>Age</option>
</select>
Try this:
Use this function in ur script:
function setday(id,elementname)
{
document.getElementById(elementname).value=id;
}
Use this in ur php form, Repeat the same code for year and month dropdowns:
if (isset($_GET['daydropdown']))
{
echo "<script type='text/javascript'>setday('".$_GET['daydropdown']."','daydropdown')</script>";
}
Related
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>
I know only this method. this method is assume that you know the values in all <option>
<select name="agama" id="agama">
<option value="Islam"<?php if ($rows['agama'] === 'Islam') echo ' selected="selected"'>Islam</option>
<option value="Khatolik"<?php if ($rows['agama'] === 'Khatolik') echo ' selected="selected"'>Khatolik</option>
<option value="Protestan"<?php if ($rows['agama'] === 'Protestan') echo ' selected="selected"'>Protestan</option>
<option value="Hindu"<?php if ($rows['agama'] === 'Hindu') echo ' selected="selected"'>Hindu</option>
<option value="Buddha"<?php if ($rows['agama'] === 'Buddha') echo ' selected="selected"'>Buddha</option>
<option value="Lain-Lain"<?php if ($rows['agama'] === 'Lain-Lain') echo ' selected="selected"'>Lain-Lain</option>
</select>
.... the above code is example from other people not mine.
but My case is the <option> is select from database too.
I have 2 table, oav_event and oav_album
the oav_album has foreign key (event_id) from oav_event table
I want to check if row['event_id'] from oav_album table is equal to option value (from oav_event table) if true, then set selected="selected"
while($row = mysqli_fetch_assoc($result)) { ?>
<option value="<?php echo $row['event_id']; ?>" >Event: <?php echo $row['event_date']; ?> </option>
<?php } ?>
the option will change depend on change in database table, so I don't know the value in option. How should I do?
<select name="event_id">
<?php
$sql = "SELECT * FROM oav_event";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$selected = "";
if($row['event_id'] == $Yourmatchvalue)
{
$selected = "selected";
}
?>
<option value="<?php echo $row['event_id']; ?>" selected="<?php echo $selected; ?>" >Event: <?php echo $row['event_date']; ?> </option>
<?php } ?>
</select>
may this helps your. you need to replace $Yourmatchvalue variable with your variable.
You can use $_GET as the method on your form and pass the id of the record using it:
while($row = mysqli_fetch_assoc($result)) {
if (!empty($_GET['event_id']) && $row['event_id'] == $_GET['event_id']) {
$selected = 'selected = "selected"';
} else {
$selected = '';
}
echo '<option '.$selected.' value="'.$row["event_id"].'">'.$row["event_date"].'</option>';
}
Here is a solution,
$selected_value = 'Hindu'; // This will come from database
Change option tag with this
<option value="<?php echo $row['event_id']; ?>" <?php echo ($row['event_id'] == $selected_value) ? 'selected="selected"' : ''; ?> >Event: <?php echo $row['event_date']; ?> </option>
Create one function which will create options list like this:
function setDropdownValue($selectQueue_list,$selectedVal)
{
$queueVal = '';
$selectQueue_list_res=$db->query($selectQueue_list);
while($selectQueue_list_res_row=$db->fetchByAssoc($selectQueue_list_res))
{
$val = $selectQueue_list_res_row['id'];
$name = $selectQueue_list_res_row['name'];
if($val == $selectedVal)
{
$queueVal .= "<option value='$val' selected='selected' label='$name'>$name</option>";
}
else
{
$queueVal .= "<option value='$val' label='$name'>$name</option>";
}
}
return $queueVal;
}
Then create a query:
$get_value_query="SELECT id, name FROM table";
$dropdown_selected_value = !empty($dropdown_value) ? $dropdown_value: ''; // Pass value which you want to be selected in dropdown
Then call this function:
$dropdown_options = setDropdownValue($get_value_query, $dropdown_selected_value);
Later when you get dropdown options in $dropdown_options, use jquery to populate the dropdown, like this:
$('#dropdown_select_id').html("$dropdown_options");
Give it a try, and let me know.
Ok so I have three tables which contains list World's countries their states and their cities for my registration form. The problem is that the list of the cities is too huge. It contains 48,314 entries in total. So my site is getting hanged and the browser is showing messages to stop script. I am using mozilla for browser purpose.
This is the code I am using to get the cities, states and countries:
$country = "SELECT * FROM countries";
$country = $pdo->prepare($country);
$country->execute();
$state = "SELECT * FROM states";
$state = $pdo->prepare($state);
$state->execute();
$city = "SELECT * FROM cities";
$citq = $pdo->prepare($city);
$citq->execute();
This is my jQuery code:
$(document).ready(function () {
$("#country").change(function() {
if ($(this).data('options') == undefined) {
$(this).data('options', $('#state option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#state').html('<option value="">Select State</option>').append(options);
});
$("#state").change(function() {
if ($(this).data('options') == undefined) {
$(this).data('options', $('#city option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#city').html('<option value="">Select City</option>').append(options);
});
});
This is my HTML:
<select name="country" id="country">
<option value="">Select Country</option>
<?php while($i = $country->fetch()){ extract($i); ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<select name="state" id="state">
<option value="">Select State</option>
<?php while($j = $state->fetch()){ extract($j); ?>
<option value="<?php echo $country_id; ?>" data="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<select name="city" id="city">
<option value="">Select City</option>
<?php while($k = $citq->fetch()){ extract($k); ?>
<option value="<?php echo $id ; ?>" data="<?php echo $state_id; ?>"><?php echo $name ; ?></option>
<?php } ?>
</select>
Now can anyone please help me getting a solution as to how I can load it completely smoothly without getting my site hanged whenever the page is refreshed?
You could load the states and cities dynamically once the "parent" selection is made. This would reduce the amount of data.
No clear code because I think you know what you are doing, but the idea:
-> [html] select
-> [js] onChange call php with ajax
-> [php] SQL select states where country="chosencountry"
-> [js] update form/selectbox
EDIT: (code)
JS:
<script>
function BuildSelectbox(job,parent) {
try { req = window.XMLHttpRequest?new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { /* No AJAX Support */ }
req.open('get','subselects.php?job='+job+'&parent='+parent);
/* let the php echo the resultvalue */
req.onreadystatechange = function() {
handleResponse(div);
};
req.send(null);
}
function handleResponse(div) {
if ((req.readyState == 4) && (req.status == 200)) {
document.getElementById(job).value=req.responseText;
}
}
</script>
PHP part: (subselects.php)
<?
if ($_GET["job"]=="states") {
// assuming there is a key country in states
$state = "SELECT * FROM states where country=".$_GET["parent"];
$state = $pdo->prepare($state);
$state->execute();
} else {
// assuming there is a key state in cities
$city = "SELECT * FROM cities where state=".$_GET["parent"];
$citq = $pdo->prepare($city);
$citq->execute();
}
// echo the whole selectbox
echo '<select id="'.$_GET["job"].'">';
// put the option loop from your queryresult here
echo '</select>';
?>
HTML:
<div id="countries" onChange="BuildSelectbox('states',this.selectedIndex);>
<select name="country" id="country">
<option value="">Select Country</option>
<?php while($i = $country->fetch()){ extract($i); ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
</div>
<div id="states"></div>
<div id="cities"></div>
This dynamically generates full selectboxes and puts them into the empty divs "states and "cities". Of course you need to output the selectbox in the php code. Parent of states is country and parent of cities is states. Hope this explains it.
I have this select , i wanna save each value after change , save it and use in other select
This is my code :
<?
$sql = "SELECT * FROM championnat ";
$result = $conn->query(sprintf($sql));
if($result){
if ($result->num_rows != 0)
{
$rows=array();
?>
<select name="nom_championnat" id="nom_championnat" >
<option value=""></option>
<?php
while($r=mysqli_fetch_assoc($result))
{
?>
<option value=" <?php echo $r['idChampionnat']?>" name="nom_championnat" selected >
<?php echo $r['nomChampionnat'] ?></option>
<?php
}
}
}
?>
</select>
</div>
I need the variable $r['idChampionnat'] to save it in each select and use it in this requete , how can it asve and put it in that requete sql ????
<?php
$sql = "SELECT * FROM equipe where idChampionnat=???? ";
$result = $conn->query(sprintf($sql));
if($result){
if ($result->num_rows != 0)
{
$rows=array();
?>
<select name="equipe1" >
<option value=""></option>
<?php
while($r=mysqli_fetch_assoc($result))
{
?>
<option required value=" <?php echo $r['nomEquipe']?>" name="equipe1" selected ><?php echo $r['nomEquipe'] ?>
</option>
<?php
}
}
}
?>
</select>
just to clear it ,
You need to use jQuery to fire an AJAX call when the first box is selected.
Its been a while since I've done this but this should give you some idea. I took some code from here and here as example
Say your html looks like this
<select id="nom_championnat">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select id="equipe1"></select>
then you need to tell jquery what to do when nom_championnat changes selection
$('#nom_championnat').change(function() {
var data = "";
$.ajax({
type:"POST",
url : "queryfile.php",
data : "value="+$(this).val(),
async: false,
success : function(response) {
data = response;
return response;
},
error: function() {
alert('Error occured');
}
});
var string = data.message.split(",");
var array = string.filter(function(e){return e;});
var select = $('equipe1');
select.empty();
$.each(array, function(index, value) {
select.append(
$('<option></option>').val(value).html(value)
);
});
});
and then you need a queryfile.php to handle the ajax requests, something like
<?php
print_r($_POST);
$value = $_POST["value"];
$sql = "select where {$value} ..."
$result = execute($sql);
echo $result;
?>
hope you fine and well,
i have a drop down list that contains categories list as follows:
<div class='form-group'>
<br/>
<label class='control-label col-md-2 'for='id_date'>Category</label>
<div class='col-md-2' class='form-group' class='col-md-11'>
<select class="form-control " id="sel1" ng-model="category" ng-init="" >
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('my');
$sql = "SELECT category FROM categories";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['category'] . "'>" . $row['category'] . "</option>";
} ?>
</select>
</div>
</div>
below this select, i have another select which is to choose element from the category as follows :
<div class='form-group'>
<br/>
label class='control-label col-md-2 ' for='id_date'>element</label>
<div class='col-md-2' class='form-group' class='col-md-11'>
<select class="form-control" id="sel12" ng-model="elemnt" ng-init="" >
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('my');
$sql = "SELECT element FROM elements where category = ";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['element'] . "'>" . $row['element'] . "</option>";
} ?>
</select>
</div>
</div>
how i can make the content of the second drop list to be based on the first drop list ?! e.g how i can put the input of the first drop list in the second SQL statement ?!
regards.
You can't do that with only php.
You must use javascript/Jquery and ajax.
Make a php script who load data from a request.
After change your first select use ajax function who call your php script with the right value and update the second select.
<select class="form-control " id="sel1" ng-model="category" ng-init="" >
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('my');
$sql = "SELECT category FROM categories";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['category'] . "'>" . $row['category'] . "</option>";
} ?>
</select>
Jquery
$("#sel1").change(function(){
$.ajax({
method: "POST",
url: "yourscript.php",
data: {myval : $(this).val()};
})
.done(function( msg ) {
//Here append your result in your second select
});
});
PHP
<?php
if(isset($_POST['myval']))
{
//SQL query where id=myval
echo $result;//result of query
}
Using pure PHP with intermediate submit:
<?php
if(isset($_POST['submitForm']) && $_POST['submitForm'] == 1){
//form is submitted by button, proceed with DB stuffs
echo 'Great, you have submitted the form, will check VALUES and do INSERT.';
}
?>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" name="aForm">
<input type="hidden" name="submitForm" id="submitForm">
<select name="category" onchange="this.form.submit();">
<option value="">Choose...</option>
<option value="1" <?=($_POST['category']==1 && !$_POST['submitForm'])?'selected':'';?>>Cat 1</option>
<option value="2" <?=($_POST['category']==2 && !$_POST['submitForm'])?'selected':'';?>>Cat 2</option>
<option value="3" <?=($_POST['category']==3 && !$_POST['submitForm'])?'selected':'';?>>Cat 3</option>
</select>
<select name="element">
<?php
if($_POST['category'] && !$_POST['submitForm']){
// SELECT from DB based on passed category ID
echo '<option value="">Now choose element...</option>';
echo '<option value="1">Elem 1</option>';
echo '<option value="2">Elem 2</option>';
echo '<option value="3">Elem 3</option>';
}else{
echo '<option value="">Choose category first...</option>';
}
?>
</select>
<input type="button" name="btnSubmit" value="Submit" onclick="document.getElementById('submitForm').value = 1; this.form.submit();">
</form>
</body>
However this is not either the best or most efficient approach, the script only demostrates how can be done without JS as is requested.