How to keep form items selected after post request.Using onchange - php

I have a problem when submit form value from the second select don't show. Can someone explain me what I'm doing wrong because in new in this (maybe is because i use onchange event). Thanks in advance.
index.php
<?php
include("includes/conn.php");
$sql = "SELECT * FROM opstina";
$result = $conn->query($sql);
if($result->num_rows > 0){
$opstineArr = array();
while($row = $result->fetch_assoc()){
$opstineArr[] = $row;
}
}
if(isset($_POST["addNesto"])){
$opstine = $_POST["opstine"];
$ime = $_POST["ime"];
if(isset($opstine)){
if(empty($opstine)){
$error["opstine"] = "izaberite opstinu";
}
}
$naselja = $_POST["naselja"];
if(isset($naselja)){
if(empty($naselja)){
$error["naselja"] = "izaberite naselje";
}
}
if(isset($ime)){
if(empty($ime)){
$error["ime"] = "izaberite ime";
}
}
if(count($error) == 0){
echo 2222;
}
}
include("includes/header.php");
?>
<form action="" method="POST">
<select name="opstine" class="form-control" id="select_id" onchange="getNaselja(this.value)">
<option>..Izaberite Opstinu..</option>
<?php foreach($opstineArr as $key => $opstina): ?>
<option value="<?php echo $opstina['OpstinaID']; ?>" <?php if(isset($opstine) && $opstine==$opstina['OpstinaID']) echo "selected"; ?> ><?php echo $opstina['NazivOpstine']; ?></option>
<?php endforeach; ?>
</select>
<?php if(isset($error["opstine"])) echo $error["opstine"]; ?>
<p>
<select name='naselja' id='naseljeLista' class='form-control' style='margin-top:10px;'>
</select>
<span><?php if(isset($error["naselja"])) echo $error["naselja"]; ?></span>
</p><br>
<input type="text" name="ime" value="<?php if(isset($ime)) echo $ime; ?>" class="form-control col-md-7 col-xs-12"><?php if(isset($error["ime"])) echo $error["ime"]; ?><br><br>
<input type="submit" name="addNesto" class="btn btn-sm btn-success">
</form>
<?php include("includes/footer.php"); ?>
getNaselja.php
global $conn;
include("includes/conn.php");
if(!empty($_POST["opstina_id"])){
$opstinaID = $_POST["opstina_id"];
$sql1 = "SELECT * FROM naselje WHERE OpstinaID=".$opstinaID;
$result1 = $conn->query($sql1);
if($result1->num_rows > 0){
$naseljaArr = array();
while ($one = $result1->fetch_assoc()) {
$naseljaArr[] = $one;
}
}
echo "<option value=''>---Izaberite naselje---</option>";
foreach ($naseljaArr as $key => $value) {
if(isset($_POST["naselja"]) && $value["NaseljeID"]==$_POST["naselja"]){
echo "<option value='".$value['NaseljeID']."' selected='selected' style='display:block;'>".$value['NazivNaselja']."</option>";
}else{
echo "<option value='".$value['NaseljeID']."'>".$value['NazivNaselja']."</option>";
}
}
}
footer.php
<script>
function getNaselja(val){
$.ajax({
type: 'POST',
url: 'getNaselja.php',
data: 'opstina_id='+val,
success: function(data){
$('#naseljeLista').html(data);
console.log(data);
}
});
}
</script>
example of form after submit on index.php
When I choose from first select my data on the console looks like:
<option value=''>---Izaberite naselje---</option>
<option value='4610'>Beška</option>
<option value='4611'>Inđija</option>
<option value='4612'>Jarkovci</option>
<option value='4613'>Krčedin</option>
<option value='4614'>Ljukovo</option>
<option value='4615'>Maradik</option>
<option value='4616'>Novi Karlovci</option>
<option value='4617'>Novi Slankamen</option>
<option value='4618'>Slankamenački Vinogradi</option>
<option value='4619'>Stari Slankamen</option>
<option value='4620'>Čortanovci</option>

Related

Undefined index in php inside selected drop down

this is the undefined error that i got
the update is working. but after i clicked the submit button, the selected dropdown gave me this error.
$row=array();
if (isset($_GET['typeid'])) {
$sql = "SELECT * FROM vehicletype WHERE id_vehicleType=" . $_GET['typeid'];
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
}
// update record
if(isset($_POST['submit'])){
$id = mysqli_real_escape_string($link,$_POST['idtype']);
$type = mysqli_real_escape_string($link, $_POST['type']);
$status = mysqli_real_escape_string($link, $_POST['status']);
$update = mysqli_real_escape_string($link, $_SESSION['idinfostaf']);
$result = mysqli_query($link, "UPDATE vehicletype SET vehicle_Type='$type', status_vehicleType='$status', updateby_vehicleType='$update' WHERE id_vehicleType=".$id);
if ($result) {
$success = "Record updated successfully!";
}
else {
$error = "Error updating record...";
}
}
i put the php code and html on the same page..below is the html
<div class="form-group">
<label>Choose Vehicle Type Status</label>
<select class="form-control" name="status" required class="form-control" value="<?php if(isset($row['status_vehicleType'])){ echo $row['status_vehicleType'];} ?>">
<option value="">Select Vehicle Type</option>
<option
value="1" <?php if ($row['status_vehicleType']==$_GET["typeid"]) { echo 'selected="selected"' ;} ?> >Enabled</option>
<option
value="0" <?php if ($row['status_vehicleType']== $_GET["typeid"]) { echo 'selected="selected"' ;} ?> >Disabled</option>
</select>
<hr>
<button type="submit" name="submit" class="btn btn-info">Submit </button>
<span class="text-success"><?php if (isset($success)) { echo $success; } ?></span>
<span class="text-danger"><?php if (isset($error)) { echo $error; } ?></span>
i used the typeid to carry the values.
Try this:
<select value="<?php if(isset($row['status_vehicleType'])){ echo $row['status_vehicleType'];} ?>">
<option value="">Select Vehicle Type</option>
<option value="1" <?php
if(isset($row['status_vehicleBrand'])) {
if ($row['status_vehicleBrand']==$_GET["typeid"]) {
echo 'Selected' ;
}
} ?> >Enabled</option>
<option value="0" <?php
if(isset($row['status_vehicleBrand'])) {
if ($row['status_vehicleBrand']==$_GET["typeid"]) {
echo 'Selected' ;
}
} ?> >Disabled</option>
</select>

Creating a dynamic Button for my multiple dropdown lists

I jut created a dynamic dropdown list that are dependant on each other on Comugg.com. Heres the code.
function dropdownmenu() {
include_once "connection.php";
?>
<div class="make">
<label>Make</label>
<select name="make" id="makelist" onchange="getId(this.value);">
<option value="">Select Make</option>
<?php
$query = "select distinct(Make) from websitemasterlist order by Make ASC";
$results = mysqli_query($conn, $query);
foreach($results as $info) {
?>
<option value="<?php echo $info[Make]; ?>"><?php echo $info[Make]; ?></option>
<?php
}
?>
</select>
</div>
<div id="model">
<label>Model</label>
<select name="model" id="modellist" onchange="getId2(this.value);">
<option value="">Select Model</option>
</select>
</div>
<div id="year">
<label>Year</label>
<select name="year" id="yearlist" onchange="getId3(this.value);">
<option value="">Select Year</option>
</select>
</div>
<button id="dropdownbutton" onclick="dropdownbutton()" class="vc_general vc_btn3 vc_btn3-size-md vc_btn3-shape-rounded vc_btn3-style-3d vc_btn3-color-success">Dropdown</button>
<script>
function getId(val){
jQuery.ajax({
method: "POST",
url: "getdata.php",
data: "make="+val,
success:function(data){
jQuery("#modellist").html(data);
}
});
}
function getId2(val){
jQuery.ajax({
method: "POST",
url: "getdata.php",
data: "model="+val,
success:function(data){
jQuery("#yearlist").html(data);
}
});
}
function dropdownbutton(val){
}
</script>
<?php
}
and heres my getdata.php
<?php
include_once "connection.php";
$make = $_POST["make"];
$model= $_POST["model"];
if (!empty($_POST["make"])) {
$make = $_POST["make"];
echo $query = "SELECT Distinct Model FROM websitemasterlist where Make='".$make."'";
$results = mysqli_query($conn, $query);
?>
<option value="">Select Model</option>
<?php
foreach ($results as $info){
?>
<option value="<?php echo $info["Model"]; ?>"><?php echo $info["Model"]; ?></option>
<?php
}
}
if (!empty($_POST["model"])) {
$model = $_POST["model"];
echo $model;
echo $query = "SELECT Distinct Year FROM websitemasterlist where Model='".$model."'";
$results = mysqli_query($conn, $query);
?>
<option value="">Select Year</option>
<?php
foreach ($results as $info){
?>
<option value="<?php echo $info["Year"]; ?>"><?php echo $info["Year"]; ?></option>
<?php
}
}
?>
Im trying to figure out how to go about creating a dynamic link. For example i wanted to do something like this but i am unsure of how to get the selected values from each field.
<a href="http://comugg.com/category/<?php echo $year; ?>/<?php echo $make; ?>/<?php echo $model; ?>>text</a>
How should i go about this?

Database driven select box being empty on submit

I am trying to submit a form value in a database with php. In form a select box value comes from database.
<?php include_once 'header.php';
$sql="SELECT uid,name FROM emitra_basic where block='$user'";
$result = $conn->query($sql);
//form validion
if(isset($_POST['submit']))
{
$eid =$_POST["eid"];
if($eid=="blank")
{
$flag=1;
$idErr="please Select E-MITRA";
}
$miatm =trim($_POST["miatm"]);
if(empty($miatm) || !preg_match("/^[a-zA-Z0-9 ]*$/",$miatm)) {
$flag=1;
$miErr="Please Enter Valid Id";
}
.............like this
if($flag==0)
{
$sqll="insert into **********";
}
//my form is
<form id="basic" method="post" name="basic">
<select class="select-style gender" name="eid">
<option value="blank">Please Select E-MITRA ID</option>
<?php
while($row=mysqli_fetch_array($result))
{
?>
<option value="<?php echo $row['uid']; ?>"><?php echo $row['uid']." (" . $row['name'] .")"; ?></option>
<?php
}
?>
</select>
<p class="contact"><label for="bid">Micro-ATM Serial No</label></p>
<input type="text" name="miatm" value ="<?php if (isset($miatm)) echo $miatm; ?>" /> <?php echo $miErr; ?>
<p class="contact"><label for="bid">Micro-ATM TID No</label></p>
<input type="text" name="tid" value ="<?php if (isset($tid)) echo $tid; ?>" /> <?php echo $tiErr; ?>
<input class="buttom" name="submit" id="submit" value="Add Me" type="submit">
Its seems Ok.but when i tried to submit the form if some of one field remain empty then its show blank value in select box.
how can i remain the same selected value in select box even if textbox remain empty.
You need to retain the value of drop down after form submit.
User selected attribute of select option.
<?php
if (isset($_POST['submit'])) {
$eid =$_POST["eid"];
if ($eid=="blank") {
$flag=1;
$idErr="please Select E-MITRA";
}
}
$sql="SELECT uid,name FROM emitra_basic where block='$user'";
$result = $conn->query($sql);
?>
<select class="select-style gender" name="eid">
<option value="blank">Please Select E-MITRA ID</option>
<?php
while($row=mysqli_fetch_array($result)) {
$selected = (isset($_POST["eid"]) && $_POST["eid"] == $row['uid']) ? 'selected="selected"' : '';
?>
<option value="<?php echo $row['uid']; ?>" <?php echo $selected;?>><?php echo $row['uid']." (" . $row['name'] .")"; ?></option>
<?php
}
?>
</select>
You need to use selected="" or selected="selected" after submission in your select tag as a attribute as:
<?
$sql="SELECT uid,name FROM emitra_basic where block='$user'";
$result = $conn->query($sql);
?>
<select class="select-style gender" name="eid">
<option value="blank">Please Select E-MITRA ID</option>
<?php
while($row=mysqli_fetch_array($result))
{
$selected = ((isset($_POST["eid"]) && $_POST["eid"] == $row['uid']) ? 'selected=""' : '');
?>
<option <?=$selected?> value="<?php echo $row['uid']; ?>"><?php echo $row['uid']." (" . $row['name'] .")"; ?></option>
<?php
}
if(isset($_POST['submit']))
{
$eid = $_POST["eid"];
if($eid=="blank")
{
$flag=1;
$idErr="please Select E-MITRA";
}
?>
</select>
Side Note:
In your question ist two lines are not inside the php, i hope this is type error.

Refine Results with dropdown box

I would like to refine the results of mysql query using dropdown boxes... live site is here:
http://www.halfwayenterprises.com/search/tyrell.php
<form name="doublecombo" action="" method="POST">
<label for="status">Status:</label>
<label for="current">
<input class="radio_style" id="current" checked="checked" name="status" type="radio" value="current">
Current
</label>
<label for="obsolete">
<input class="radio_style" id="obsolete" name="status" type="radio" value="obsolete">
Obsolete
</label>
<label for="both">
<input class="radio_style" id="both" name="status" type="radio" value="both">
ALL
</label>
<br /><br />
<select name="category" size="1" onChange="redirect(this.options.selectedIndex)">
<option value="null">Category</option>
<option value="asset management">Asset Management</option>
<option value="budget">Budget/Finance</option>
<option value="central office">Central Office</option>
<option value="disposal">Disposal</option>
</select>
<select name="subcategory">
<option value="null">Sub-Category</option>
<option value="Portfolio">Portfolio</option>
<option value="Pricing">Pricing</option>
<option value="Valuation">Valuation</option>
<option value="Disposal">Disposal</option>
</select>
<input name="submitted" type="submit" value="GO">
<br />
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option id="title" VALUE="title">Title</option>
<Option id="poc" VALUE="poc">POC</option>
<Option id="purpose" VALUE="purpose">Purpose</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input name="submitted" type="submit" value="GO">
</form>
<select name="filter1">
<option value="az">Sort by A-Z</option>
<option value="date">Sort by Date</option>
</select>
<select name="filter2">
<option value="office">Sort by Office</option>
<option value="p">P</option>
<option value="pt">PT</option>
<option value="pf">PF</option>
</select>
<select name="filter3">
<option value="mandatory">Mandatory</option>
<option value="nonmandatory">Non-Mandatory</option>
<option value="combined">Combined</option>
</select>
</form>
</p>
<script>
<!--
/*
Double Combo Script Credit
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free JavaScripts here!
*/
var groups=document.doublecombo.category.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=new Option("Sub Category")
group[1][0]=new Option("Portfolio")
group[1][1]=new Option("Pricing")
group[1][2]=new Option("Valuation")
group[3][0]=new Option("Central Office")
group[4][0]=new Option("Disposal")
var temp=document.doublecombo.subcategory
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function go(){
location=temp.options[temp.selectedIndex].value
}
//-->
</script>
<?
mysql_connect("localhost", "name", "pasword") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
if(isset($_POST["submitted"])){
$status = $_POST['status'];
$category = $_POST['category'];
$subcategory = $_POST['subcategory'];
echo '<div class="status_div">';
if($status=='current')
{
echo "<h2>Results</h2><p>";
$res = mysql_query("SELECT * FROM material WHERE status='$status' AND category='$category' AND subcategory='$subcategory' ORDER BY `documentid` ASC");
while ($row = mysql_fetch_assoc($res)) {
echo '<div class="current">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
} if ($status=='obsolete')
{
echo "<h2>Results</h2><p>";
$res = mysql_query("SELECT * FROM material WHERE status='$status' AND category='$category' ORDER BY `documentid` ASC ");
while ($row = mysql_fetch_assoc($res)) {
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '<br>';
}
} if ($status=='both')
{
echo "<h2>Results</h2><p>";
$res = mysql_query("SELECT * FROM material WHERE status1='both' AND category='$category' ORDER BY `documentid` ASC");
while ($row = mysql_fetch_assoc($res)) {
echo '<div class="">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
}
echo '</div>';
}
$field = #$_POST['field'] ;
$find = #$_POST['find'] ;
$searching = #$_POST['searching'] ;
$status = $_POST['status'];
//This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo "<h2></h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<a href='tyrell.htm'>Return</a>";
exit;
}
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
if($status=='current'){
$data = mysql_query("SELECT * FROM material WHERE status='$status' AND lower($field) LIKE'%$find%' LIMIT 0,30");
while ($row = mysql_fetch_assoc($data)) {
echo '<div class="current">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
}
if ($status=='obsolete'){
$data = mysql_query("SELECT * FROM material WHERE status='$status' AND lower($field) LIKE'%$find%' LIMIT 0,30");
while ($row = mysql_fetch_assoc($data)) {
echo '<div class="obsolete">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
} if ($status=='both'){
$data = mysql_query("SELECT * FROM material WHERE status1='both' AND lower($field) LIKE'%$find%' LIMIT 0,30");
while ($row = mysql_fetch_assoc($data)) {
echo '<div class="">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
<p align="center"><font face="arial" size="-2">This free script provided by</font><br>
<font face="arial, helvetica" size="-2"><a href="http://javascriptkit.com">JavaScript
Kit</a></font></p>'
</body>
</html>
I have can't think of how to use the drop downs without having a submit button
I think I know what you need...
Use jquery to submit form on you page.
Something like this...
$("submitted").click(function() {
var url = "file.php";
$.ajax({
type: "POST",
url: url,
data: $("doublecombo").serialize(), // serializes the form's elements.
success: function(data)
{
// populate box or div with your result
}
});
return false; // avoid reload.
});
//PHP part
if($_POST['someField']){
$result = //Do query and staff and return any type of resposne you will handle in ajax success
echo $result;
exit;
}
You can use JavaScript to manipulate the content of the dropdown list. All you need is to do is bind the click even on the radio button and when one of them gets clicked, use an Ajax call to retrieve the information from your SQL database and modify the content of your selectbox.
EDIT
Here's some code you can add to your page:
$('form[name=doublecombo] input').change(function() {
$('form[name=doublecombo]').submit();
});
Note that change might not work. If it doesn't, try using click instead.

Echo drop down value from database

I have my textboxe showing the data that is in the correct field from the database, but not when it is a drop down (select)
I have tried this code
<?php
$rs_settings = mysql_query("SELECT * from thesis WHERE user_id = $user_id;");
?>
<form action="academic.php" method="post" name="regForm" id="regForm" >
<?php
$num_rows = mysql_num_rows($rs_settings);
if($num_rows > 0) { ?>
<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
1a.question <span
class="required">*</span></td>
<select name="Applied_Elsewhere" id="Applied_Elsewhere" >
<option <? if ($row_settings[Applied_Elsewhere]=='Y') { ?> selected <? } ?>
value="Y">Yes </option>
option <? if ($row_settings[Applied_Elsewhere]=='N') { ?> selected <? } ?>
value="N">No </option>
</select>
Try changing <? to <?php and $row_settings[Applied_Elsewhere] to $row_settings['Applied_Elsewhere']
<select name="Applied_Elsewhere" id="Applied_Elsewhere" >
<option <?php if($row_settings['Applied_Elsewhere']=='Y') { echo "selected='selected'"; } ?> value="Y">Yes </option>
<option <?php if($row_settings['Applied_Elsewhere']=='N') { echo "selected='selected'"; } ?> value="N">No </option>
</select>
Please try this code:
<?php
$rs_settings = mysql_query("SELECT * from thesis WHERE user_id = $user_id;");
?>
<form action="academic.php" method="post" name="regForm" id="regForm" >
<?php
$num_rows = mysql_num_rows($rs_settings);
if($num_rows > 0) {
while ($row_settings = mysql_fetch_array($rs_settings)) {
1a.question <span
class="required">*</span></td>
print'<select name="Applied_Elsewhere" id="Applied_Elsewhere" >'
if ($row_settings['Applied_Elsewhere']=='Y')
print '<option value="Y" selected>Yes </option>';
else
if ($row_settings['Applied_Elsewhere']=='N')
print '<option value="N" selected>No</option>';
?>

Categories