keep value selected on multiple ajax dropdowns after submit - php

i have the following dropdown box:
page index.php
<script type="text/javascript">
$(document).ready(function() {
$('#loader').hide();
$('#show_heading').hide();
$('#search_category_id').change(function(){
$('#show_sub_categories');
$('#loader').show();
$.post("get_chid_categories.php", {
kwdikos: $('#search_category_id').val(),
}, function(response){
setTimeout("finishAjax('show_sub_categories', '"+escape(response)+"')", 400);
});
});
});
function finishAjax(mhnas_exodwn, response){
$('#loader').hide();
$('#show_heading').show();
$('#'+mhnas_exodwn).html(unescape(response));
$('#'+mhnas_exodwn).fadeIn();
}
function alert_id()
{
if($('#sub_category_id').val() == '')
alert('Please select a sub category.');
else
alert($('#sub_category_id').val());
return false;
}
</script>
<style>
.both h4{ font-family:Arial, Helvetica, sans-serif; margin:0px; font-size:14px;}
#search_category_id{ padding:3px; width:200px;}
#sub_category_id{ padding:3px; width:100px;}
.both{ float:left; margin:0 15px 0 0; padding:0px;}
</style>
</head>
<?php
include('dbcon.php');?>
<body>
<div style="padding-left:30px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" name="form" method="post" enctype="multipart/form-data">
<div class="both">
<select name="search_category" id="search_category_id">
<option value="" selected="selected">Πολυκατοικία</option>
<?php
$query = "SELECT DISTINCT polykatoikia,kwdikos FROM exoda ORDER BY polykatoikia ASC";
$results = mysql_query($query);
while ($rows = mysql_fetch_assoc(#$results))
{
echo "<option ". (($_REQUEST['search_category'] == $rows["kwdikos"]) ? 'selected ' : '') ."value=\"".$rows["kwdikos"]."\">".$rows["polykatoikia"]."</option>";?>
<!-- <option value="<?php echo $rows['kwdikos'];?>"><?php echo $rows['polykatoikia'];?></option>-->
<?php
}?>
</select>
</div>
<div class="both">
<div id="show_sub_categories" align="center">
<img src="loader.gif" style="margin-top:8px; float:left" id="loader" alt="" />
</div>
</div>
<? echo "<p><input type = 'hidden' value=$rows[mhnas_exodwn] name='mhnas'</p>"; ?>
<input type="submit" class="button small gray" name="" value="sumbit" />
</form>
</div>
here's the get_chid_categories.php:
<?php
include('dbcon.php');
if($_REQUEST)
{
$id = $_REQUEST['kwdikos'];
$query = "select distinct kwdikos,mhnas_exodwn from 010_08_exoda where kwdikos= ".$id;
$results = mysql_query( $query);?>
<select name="sub_category" id="sub_category_id">
<option value="" selected="selected">Μήνας</option>
<?php
while ($rows = mysql_fetch_assoc(#$results))
{
<option value="<?php echo $rows['mhnas_exodwn'];?>"><?php echo $rows['mhnas_exodwn'];?></option>
<?php
}?>
</select>
<?php
}
?>
as you can see i can keep selected the first combobox value after submit, how i can keep the second dropdown value shown?
After i submit, the second dropdown disappears.
thanks

You have two options:
1) After the user submitted the form - using the server side you will need to analyze the content of the POST header - or if your form use GET, you will need to parse the querystring (that's something that you can also do using javascript)
2) You validate your form without the 'submit' action but by using an Ajax call. This Ajax call can return you an error code based on the error made by the user and then you can update the user interface accordingly.
I recommend the second option. You have a good example here

Related

Create session from drop down list items

I have created a drop-down list that shows the members which have been added from the user. The script for this is this one:
<?php include('server.php'); ?>
<?php
$connect = mysqli_connect("localhost", "root", "", "geofence");
?>
<html>
<head>
<title>Add members</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br /><br />
<h2 align="center">Please, choose a family member</h2>
<br /><br />
<div class="form-group" align="center">
<form name="dropdown" action="" method="post">
<select name="choose" id="choose" width="150" style="width: 150px">
<option value="" selected disabled hidden>Choose Member</option>
<?php
$res=mysqli_query($connect,"select *
from member
where user_id=".$_SESSION['user_id']."");
while($row=mysqli_fetch_array($res)) {
?>
<option><?php echo $row["name"]; ?></option>
<?php
}
?>
</select>
</form>
<input type="button" name="ok" id="ok" class="btn btn-info" value="OK" />
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#ok').click(function(){
$(location).attr('href', 'http://localhost/Houston/index.php')
});
});
</script>
Now, what I'm trying to do is to create a session ($_SESSION['member_id']) which refers to the name that is selected from the list. I have tried several things so far but with no success. An example is this:
if (isset($_POST['choose'])) {
if (count($errors)==0) {
$query="SELECT * FROM member where name=".$_POST['choose']."";
$result=mysqli_query($db,$query);
if (mysqli_num_rows($result)==1) {
$row=mysqli_fetch_assoc( $result);
$member_id=$row['member_id'];
$_SESSION['member_id'] = $row['member_id'];
}
}
}
I need the $_SESSION['member_id'] so I can use it on another file and populate my database. What is missing?
The problem is in the option tag, you have to specify de value of each option in the select tag , like this:
<option value="<?php echo $row["member_id"];?>"> <?php echo $row["name"]; ?> </option>
So, next you just have to declare the $_SESSION for your option value
if (isset($_POST['choose'])) {
$_SESSION['member_id']=$_POST["choose"];
}

How we can store different input fields on same column of table with their values by comma,

I want to store dynamic generated input fields in same column of the table with their individual values seperated by commas but using implode for the same is saving only data of first input type.
i have given name of input field as an array (skill[]) so that it can store multiple value
Here is my code
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function check(skill) {
const selectedSkils = $(skill).val();
$('.techInput').each(function(i, v) {
if (selectedSkils.indexOf($(v).attr('id')) !== -1) {
$(v).removeClass('hide');
} else {
$(v).addClass('hide')
}
})
}
</script>
<style>
.hide {
display: none;
}
.techInput {
margin: 5px;
padding: 5px;
border-radius: 4px;
}
</style>
</head>
<body>
<form action="submit1.php" method="post" >
<select name="skills[]" id="skills" multiple onchange="check(this);">
<option value="css">css</option>
<option value="php">php</option>
<option value="magento">magento</option>
</select>
<div id="css" class='hide techInput'>
<label for="sel1"></label><input type="text" name="skill[]" id="selc1" placeholder='css'>
</div>
<div id="php" class='hide techInput'>
<label for="sel2"></label><input type="text" name="skill[]" placeholder='php' id="selc2">
</div>
<div id="magento" class='hide techInput'>
<label for="sel3"></label><input placeholder='magento' type="text" name="skill[]" id="selc3">
</div>
<input type="submit" name="submit" id="submit">
</form>
</body>
</html>
Although select inputs are saving in database
submit1.php
<?php
require 'dbserver.inc.php';
if(isset($_POST['submit']))
{
$f_skills = mysqli_real_escape_string($conn,implode(', ', $_POST['skills']));
$f_skill = mysqli_real_escape_string($conn,implode(', ', $_POST['skill']));
$query = "INSERT INTO detail ( `f_Skills`,`f_skill`) VALUES (?,?)";
$stmtt = $conn->prepare($query);//prepared statement method
$stmtt->bind_param("ss",$f_skills,$f_skill );//binding a parameter to question mark
$stmtt->execute();
//testing purpose
echo("Reached here after executing query");
if($stmtt->affected_rows > 0)
{
echo("success");
$stmtt->close();
}
else
{
echo("fail");
}
}
else
{
echo("error occur please check");
}
?>

how to get value from dependant drop down list to javascript and parsing it to another php page?

I make a 2 level dependant drop down list and that work fine, but I don't know how to get the 2nd level value with javascript..here is the code I'm using..
dropdownlist.html:
<script type="text/javascript" src="../js/dropdown_list.js"></script>
<select class="level" id="level1" onChange="get_level2(this.value)">
<option selected="selected" value="0">--Choose One--</option>
<?php
$sql_get = mysql_query ("SELECT * FROM ajax_table WHERE pid=0");
while($row_get = mysql_fetch_array($sql_get))
{
echo "<option value='".$row_get['id']."'>".$row_get['category']."</option>";
}
?>
</select>
<span id="level2"></span>
since the dependant work just fine..so I think I can skip the get_level2 () function and another php file to process the 2nd level drop down..
and here is the code where I try to get the value from drop down list when button click..
dropdown_list.js :
function cekForm() {
//the getValue1 work fine but I can't make getValue2 work..
//how to get value from 2nd level drop down list with getValue2??
var value1 = document.getElementById("level1");
var getValue1 = value1.options[value1.selectedIndex].value;
var value2 = document.getElementById("level2");
var getValue2 = value2.options[value2.selectedIndex].value;
if (getValue1 == 0){
alert("Please Choose One");
}
if (getValue1 != 0){
//where I want to pass the dropdown value to post_value.php
window.location= "post_value.php";
}
}
How to get the value of 2nd level drop down list??and how to pass the value to post_value.php??
please help me...
Update :
Here is the code from firefox view page source:
//this is <head> part
<link href="../css/val.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../js/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="../js/dropdown_list.js"></script>
//end of </head>
//<body> part
<div class="form-div">
<form id="form_level" name="form_level" style="padding-top:0px;">
<div class="form-row" style="padding-top:0px;">
<h3>Choose Drop Down :</h3>
<select class="level" id="level1" onChange="get_level2(this.value)" style="position:relative; top:-40px; left:150px;">
<option selected="selected" value="0">--Choose One--</option>
<option value='1'>BAA</option><option value='2'>BAK</option><option value='3'>BAUK</option></select>
<span id="level2"></span>
</div>
<div class="form-row" style="position:relative; top:100px; left:305px;">
<input class="submit" value="Send" type="button" onClick="cekForm()">
</div>
<br /><br />
</form>
</div>
Pass value using get method through url
<script>
function cekForm() {
var getValue1 = document.getElementById("level1").value;
var getValue2 = document.getElementById("level2").getElementsByTagName("select")[0].value;
if (getValue1.length==0){
alert("Please Choose One");
return;
}
if (getValue1.length>0){
window.location= "post_value.php?level1="+getValue1+"&level2="+getValue2;
}
}
</script>
and receive it in php file
post_value.php
<?php
$level1 = $_GET["level1"];
$level2 = $_GET["level2"];
?>

filling combobox with data from php database

this is my code
<select>
<?php
$query = "SELECT * FROM 'sections'";
$result = mysql_query($query);
while($row=mysql_fetch_array($result)){
echo "<option value='".$row[id]."'>".$row[sectionName]."</option>";
}
?>
</select>
nothing happen I don't know why
this my page maybe there is wrong some where
<?php
ob_start();
session_start();
include('../includes/connect.php');
include('../includes/phpCodes.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>لوحة التحكم</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="../css/mainstyle.css">
<link rel="stylesheet" type="text/css" href="css/controlstyle.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#tabs div').hide();
$('#tabs div:first').show();
$('#tabs ul li:first').addClass('active');
$('#tabs ul li a').click(function(){
$('#tabs ul li').removeClass('active');
$(this).parent().addClass('active');
var currentTab = $(this).attr('href');
$('#tabs div').hide();
$(currentTab).show();
return false;
});
});
</script>
</head>
<body>
<div class="wrapper">
<?php headerCode(); ?>
<div class="content">
<div id="tabs">
<ul>
<li>اضافة موضوع</li>
<li>حذف موضوع</li>
<li>تعديل موضوع</li>
<li>التحكم بالاقسام</li>
</ul>
<div id="add">
<form method="POST" action="includes/add.php" dir="rtl" enctype="multipart/from-data">
<br>
حدد القسم :
<select>
<?php
$query = "SELECT * FROM 'sectionsd'";
$result = mysql_query($query);
while($row=mysql_fetch_array($result)){
echo "<option value='".$row[id]."'>".$row[sectionName]."</option>";
}?>
</select><br>
عنوان الموضوع :<input type="text" name="title" class="mem-information"/><br>
الموضوع : <br /><textarea name="subject" rows="10" cols="50" class="mem-information" style="width: 500px"></textarea><br /><br>
الصورة :<input type="file" name="image"><br>
<input type="submit" value="إرسال" name="send" class="log" style="color: black">
</form>
</div>
<div id="remove">
<form method="POST" action="includes/remove.php" dir="rtl"><br>
حدد القسم :
<select name ="sectionsName">
<option value="">dd</option>
</select>
<input type="submit" value="حذف" name="send" class="log" style="color: black">
</form>
</div>
<div id="edit">
</div>
<div id="addDep">
</div>
</div>
</div>
</div>
</body>
</html>
sorry for my bad English
my table
The problem I see is you are using single quotes on your table name in your query, you should either use back tick or no back ticks for table name. Please try the following code:
<?php
$query = "SELECT * FROM `sections`";
$result = mysql_query($query);
while($row=mysql_fetch_array($result, MYSQL_ASSOC)){
echo "<option value='".$row['id']."'>".$row['sectionName']."</option>";
}
?>
Also start looking into using mysqli (http://php.net/manual/en/book.mysqli.php) or PDO (http://php.net/manual/en/book.pdo.php), as mysql is deprecated.
Try this... And we are all Asuming the name of the column is "sectionsd" with the "d".
<?php
$query = "SELECT * FROM 'sectionsd'";
$result = mysql_query($query);
while($row=mysql_fetch_assoc($result)){
echo "<option value='".$row["id"]."'>".$row["sectionName"]."</option>";
}?>
</select>
If it's not working it may be due to:
1) You're using a mysql_ function and you're not sending the parameter $link to the function. Like:
mysql_query($query, $connectionlink);
2) The table name is wrong
3) You have an error: Use mysql_query() or die(mysql_error()); to see what's going on
4) DO NOT use single quotes ' around your table name in the query
echo '
<option value='.$row["id"].'>'.$row["sectionName"].'</option>
';

How do I update input values with db values after a select OnChange with idealforms?

I'm using idealforms from elclanrs and I have a select which is filled from a database. OnChange I want to update the value of the input fields with information from the database. In this case, firstname, lastname. I tried it with AJAX but that didn't work out because when the form values where getting renewed, the whole idealforms makeup of the form vanishes.
I looked through stackoverflow and saw it was a fairly common problem but I still can't seem to work it out. I used this and it didn't work, maybe because I placed it in the wrong order?
This is my code:
<form id="my-form" action="EditAccountHandler.php" method="post">
<?php
include 'conn/dbConnect.php';
echo '<div><label>Gebruikers</label><select id="gebruiker" selected="$sUsername" name="selectedUser" onchange="updateInput(this.value)">';
$sqEditUser = mysql_query("SELECT * FROM account a, persoon p WHERE a.idSuper = p.idUser", $con);
while($row = mysql_fetch_array($sqEditUser))
{
$iIdUser = $row['idUser'];
$sFirstname = $row['Voornaam'];
$sLastname = $row['Achternaam'];
$sUsername = "{$sLastname}, {$sFirstname}";
echo "<option value='$iIdUser'>$sUsername</option>";
}
echo "</select></div>";
?>
<script>
function updateInput(<?= json_encode($sFirstname); ?>)
{
document.getElementById("naam").value = <?php echo json_encode($sFirstname); ?>;
}
</script>
<div><label>Voornaam</label><input id="naam" name="naam" type="text"/></div>
<div><label>Achternaam</label><input id="anaam" name="anaam" type="text"/></div>
<div>
<button id="reset" type="button">Reset</button>
<button type="submit">Wijzigen</button>
</div>
</form>
This is what I'm trying to achieve:
Example picture
I'm not sure about what I am doing wrong. Can yo guys help me?
Edit
Removed code that was double in comparison with the first codesnippet.
Added echo
Removed action="EditAccountHandler.php"
Added idealforms validation code
Replaced with final code
<div id="main">
<h3>Wijzig Account</h3><br />
<form id="myselect" action="" method="post">
<div>
<label>Gebruikers</label><select id="gebruiker" selected="$sUsername" name="selectedUser" onchange="this.form.submit()">
<?php
include 'conn/dbConnect.php';
$sqUser = mysql_query("SELECT * FROM account a, persoon p WHERE a.idSuper = p.idUser", $con);
while($row = mysql_fetch_array($sqUser))
{
$iIdUser = $row['idUser'];
$sFirstname = $row['Voornaam'];
$sLastname = $row['Achternaam'];
$sUsername = "{$sLastname}, {$sFirstname}";
echo "<option value='$iIdUser'>$sUsername</option>";
}
?>
</select>
</div>
</form>
<script>
var options = { onFail: function(){alert('Selecteer een persoon')}};
var $myform1 = $('#myselect').idealforms(options).data('idealforms');
$myform1.focusFirst();
</script>
<?php
if(!empty($_POST['selectedUser']))
{
$sqGetUser = mysql_query("SELECT * FROM persoon WHERE idUser = '$_POST[selectedUser]'", $con);
while($row = mysql_fetch_array($sqGetUser))
{
$sFname = $row['Voornaam'];
$sLname = $row['Achternaam'];
}
?>
<form id="my-form" action="EditAccountHandler.php" method="post">
<div><label>Voornaam</label><input id="naam" name="naam" value="<?php echo htmlspecialchars($sFname); ?>" type="text"/></div>
<div><label>Achternaam</label><input id="anaam" name="anaam" value="<?php echo htmlspecialchars($sLname); ?>" type="text"/></div>
<div>
<label>Rechten</label>
<label><input type="radio" name="rechten" value="Administrator"/>Administrator</label>
<label><input type="radio" name="rechten" value="Contentmanager"/>Contentmanager</label>
<label><input type="radio" name="rechten" value="Administratie"/>Administratie</label>
<label><input type="radio" name="rechten" value="Medewerker"/>Medewerker</label>
<label><input type="radio" name="rechten" value="Klant" checked/>Klant</label>
<label><input type="radio" name="rechten" value="Gast"/>Gast</label>
<label><input type="radio" name="rechten" value="MedeKlant"/>MedeKlant</label>
</div>
<div>
<button id="reset" type="button">Reset</button>
<button type="submit">Wijzigen</button>
</div>
</form>
</div>
</div>
<script>
var options =
{
onFail: function()
{
alert( 'Vul alle velden correct in.' )
},
inputs:
{
'anaam':
{
filters: 'required name',
},
'naam':
{
filters: 'required name',
},
}
};
var $myform = $('#my-form').idealforms(options).data('idealforms');
$('#reset').click(function(){ $myform.reset().fresh().focusFirst() });
$myform.focusFirst();
</script>
<?php
}
?>
I think you are messing client code with server code.
Once the onChange event is fired, you have to reload the page for example onChange="this.form.submit()" and you verify if(!empty($_POST["selectedUser"])) then you fill the fields of the form with the data you can obtain with a new SQL query, where id = $_POST["selectedUser"].
In this case you don't need the updateuser function.
If you use AJAX, you would need the updateuser function, but you have got to get rid of the json_encode methods which execute on server, and with ajax everything is in the client part. It would be simply: "function updateuser(id)".
You can use jquery to do the ajax call to get the info, and then you fill the form fields.
EDIT:
Examining the new code you provide. I see one error, you are using htmlspecialchars function but you are not echoing it, ;-). You should use "echo ...".
For the form, you should use "this.form.submit()" if you are inside the form labels.
If you use jquery it would be something like this:
<script type="text/javascript">
$("#selectedUser").change(function()
{
if(this.form.elements['selectedUser'].value!="")
{
this.form.submit();
}
});
</script>

Categories