Dependable select box - php

I have this code :
<form id="frmKat" role="form" action="" method="post">
Country :
<select name="country" id="country">
<option>-select your country-</option>
<?php
$result=mysqli_query($kon, "SELECT * from regios");
while($country=mysqli_fetch_assoc($result)){
echo "<option value=$country[id]>$country[naam]</option>";
} ?>
</select>
City :
<select name="city" id="city">
<option>-select your city-</option>
</select>
<div style="clear:both;"></div>
<button type="submit" class="pull-right btn btn-success" name="btnConvert" id="btnConvert">Convert</button>
</form>
My ajax code is :
<script type="text/javascript">
$(document).ready(function(){
$("#country").change(function(){
var country=$("#country").val();
$.ajax({
type:"post",
url:"getcutoff.php",
data:"country="+country,
success:function(data){
$("#city").html(data);
}
});
});
});
</script>
And my getcutoff.php file is next :
<?php
session_start();
include("config.php");
global $kon;
ob_start();
if(isset($_SESSION["admin"])){
$country=$_POST["country"];
$result=mysqli_query($kon, "select * FROM cutoffs WHERE regio_id=". $country ." ");
while($city=mysqli_fetch_array($result)){
echo "<option value=$city[id]>$city[datetime]</option>";
}
}else{
ob_flush();
die("Salut");
}
?>
I'm trying to make dependable selectboxes. When user chooses something in the first selected box, then they will be taken to the second one where they can choose values which are connected to the first selected box. In first box I get values, but when I choose something in the second one, I get nothing. Where am I making a mistake?

Group your options in a php variable as string and use a single echo in getcutoff.php
$res ='';
while($city=mysqli_fetch_array($result)){ $res.="<option value=$city[id]>$city[datetime]</option>"; }
echo $res;

your echo looks a bit wrong. Also, I assume you have saved your daetime as DateTime in SQL, thus you'd need to convert it before defining it as a string.
$date = strtotime($city[datetime]);
$date = date('Y-m-d H:i:s', $date);
echo "<option value='".$city[id].">".$date."'>My Option</option>";

Related

Inserting values into database from form with drop downs

I'm trying to insert values input from the user in a form into my database.
I am trying to create 2 drop down lists, with the first deriving the options for the second. For example the first drop down list for Faculty, with the second drop-down list containing the schools within the selected faculty.
I am also then wanting to insert the gathered information into my database however I can focus on that after getting the drop-down's correct first.
My register page is on one page with the getSchool.php on a different file, I have a feeling the connection between the two could be my issue.
The register.php is below. This is the page the form is on
<?php
session_start();
include('dbConnect.php');
$queryStr=("SELECT * FROM faculty");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<html>
<head>
<TITLE>Faculty & School</TITLE>
<head>
<!-- Help for code to create dynamic drop downs -->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"
type="text/javascript"></script>
<script>
function getFaculty(val) {
$.ajax({
type: "POST",
url: "getFaculty.php",
data:'facultyID='+val,
success: function(data){
$("#schoolList").html(data);
}
});
}
function selectFaculty(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>
</head>
<body>
<div class="frmDronpDown">
<div class="row">
<label>Faculty:</label><br/>
<select name="faculty" id="facultyList" class="demoInputBox"
onChange="getFaculty(this.value);">
<option value="">Select Faculty</option>
<?php
foreach($results as $faculty) {
?>
<option value="<?php echo $faculty["facultyID"]; ?>"><?php echo
$faculty["facultyName"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<form action="addBlood.php" method="post">
<label>Test:</label><br/>
<select name="test" id="test-list" class="demoInputBox">
<option value="">Select Test</option>
</select>
</div>
</div>
<label>Result:</label><input class="input" name="result" type="text"><br>
<label>Date:</label><input class="input" name="date" type="date"><br>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
Below is the getSchool.php which gets all the schools
<?php
include('dbConnect.php');
if(!empty($_POST["facultyID"])) {
$queryStr=("SELECT * FROM school WHERE facultyID = '" . $_POST["facultyID"]
. "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<option value="">Select School</option>
<?php
foreach($results as $school) {
?>
<option value="<?php echo $school["schoolID"]; ?>"><?php echo
$school["schoolName"]; ?></option>
<?php
}
}
?>
Thanks in advance for any feedback and help.
Simon
url: "getFaculty.php",
data:'facultyID='+val,
success: function(data){
$("#schoolList").html(data);
Where is the #schoolList element ? Why getFaculty.php? Should it not be getSchool.php ?
First, just to re-iterate what was already mentioned, update your getFaculty() to get getSchool() and make sure it points to getSchool.php.
Now, you need to create a div following your first drop-down with an id schoolList.
<div class="row" id="schoolList"></div>
Now, update your getSchool.php so that it generates the full form/selection. Something along the lines of:
<?php
include('dbConnect.php');
if(!empty($_POST["facultyID"])) {
$queryStr=("SELECT * FROM school WHERE facultyID = '" . $_POST["facultyID"]
. "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<label>Schools:</label><br/>
<select name="schoolSelect" id="schoolSelect" class="demoInputBox">
<option value="">Select School</option>
<?php
foreach($results as $school) {
?>
<option value="<?php echo $school["schoolID"]; ?>"><?php echo
$school["schoolName"]; ?></option>
Once you've got those ideas down, you'll have to make sure you have the full flow of your page the way you want it. Then follow similar standards for posting any inputs to the php page you use for database manipulation.
As noted in earlier posts, this solution still leaves you vulnerable to injection. That's for another post, another day.

Retrieve data/record from the database using dropdown list without reloading

<form method="post" action="a.php">
<select name="taskOption">
<?php
include 'orderSelect.php';
echo '<option>View Order</option>';
while($row = mysqli_fetch_array($result)):;?>
<option value='<?php echo $row[0]; ?>'><?php echo $row[1]; echo " ";
echo $row[2]; ?></option>
<?php endwhile; ?>
<input type="submit" name="submit" value="click">
</select>
</form>
I want to retrieve a record/ data from the database when I select something from the dropdown list. Any advice on what to look up or code for this to be successful.
As suggested in OP tag you should be using ajax Example with JQuery below:
$('select["name=taskOption"]').change(function() {
var selected = $(this).val();
$.get('YOUR_FILE_WHICH_PROCCESS_RECORD.php',{selectVal:selected},function(data){
console.log(data);//this is the value from your php file.
})
})

Ajax Html Forms with PHP, Jquery and MYSQL,

I understand this question may be entirely juvenile however I have been trying to debug it for an entire afternoon, not using an IDE other than sublime. would be really glad to receive any help and format this question nicely for future begineers when it works.
currently
my html.
<?php
//connect to the server & database
$connect = mysqli_connect('localhost','root','root','ikea');
if(!$connect)
{
echo "failed to connect ".mysqli_connect_error();
}
// query the database
$query = 'SELECT * from department
where iconpath Like "image%"
order by name asc';
$result = mysqli_query($connect,$query);
// retrieve the resultset
while( $row[] = $result->fetch_object());
?>
<form id="question2" method="POST">
<div class="form-group input-group">
<select style="width:8.7cm;" id="member_choice" class="form-control">
<option value="">-- Select One --</option>
<?php foreach($row as $option) : ?>
<option value="<?php echo $option->name; ?>"><?php echo $option->name; ?></option>
<?php endforeach; ?>
</select><br/><br/>
<button id="q2-submit" name="q2-submit" style="margin-left:5cm;" type="submit" class="btn btn-default btn-add"> Get Departments! </button>
</div>
</form>
my jquery
$('#question2').on('submit', function()
{
alert("submit!");
// AJAX STUFF HERE
$.post('q3.php', function(data)
{
console.log("here1");
$(".return").html(data);
});
});
and currently experimenting with my php trying to get it to return "content"
<?php
echo "content";
?>
Your question keeps changing. Honestly, I recommend you go through a tutorial on how to submit a form using AJAX with jQuery, like this one.
You should use submit handler instead of a click handler. Also your selector is wrong.
HTML
added name attribute to the <select> tag.
<form id="question2" method="POST" action="q2.php">
<div class="form-group input-group">
<label>Select Member Card Number</label>
<select name="member_choice" style="width:8.7cm;" id="member_choice" class="form-control">
<option value="">-- Select One --</option>
<?php foreach($row as $option) : ?>
<option value="<?php echo $option->name; ?>"><?php echo $option->name; ?></option>
<?php endforeach; ?>
</select><br/><br/>
<button style="margin-left:5cm;" type="submit" class="btn btn-default btn-add"> Get Departments! </button>
</div>
</form>
<div id="content"></div>
JQUERY
$('#question2').on('submit', function(event)
{
// stop form from submitting normally
event.preventDefault();
var $form = $(this);
var url = $form.attr('action');
$.post(url, $form.serialize(), function(data)
{
console.log("here1");
$('#content').html(data.content);
});
});
PHP (q2.php)
<?php
$content = $_POST['member_choice'];
echo json_encode($content);
?>
Your click handler doesn't prevent the form from submitting (the page gets refreshed) so you never see the ajax response. Use a submit handler instead:
$('#question2').on('submit',function(e)
{
var name = $('#department_choice :selected').val();
console.log("here");
$(".return").html("asdad");
$.post('q2.php', function(data)
{
console.log("here1");
$(".return").html(data);
});
return false;//prevent form submit
});

related dropdown list

I'm new in PHP.. I need your help..
I have 2 dropdownlist that related:
dropdown 1 : manually insert the value
dropdown 2 : attach value from database (value based on condition that selected in dropdown 1)
Then, both value which are selected will display in textbox at another form.
My problem is:
1) The value in 2nd dropdown can't be display.
2) The value in 1st dropdown can pass to other form but the 2nd can't.
Please kindly guide me.
I don't know how to share my code here.
form1.php
//1st dropdown
<select name="fruit_name" id="fruit_name" style="font-family: Calibri;font-size: 10pt;" onchange="loadXMLDoc(this.value); ">
<option value="0">-- please choose --</option>
<option value="Pineapple">Pineapple</option>
<option value="Apple">Apple</option>
//2nd dropdown
$fruit_name = $_POST['fruit_name'];
#Connect to MySQL
#Connect to database
$result = mysql_query("SELECT colour FROM fruit WHERE fruit_name = '$fruit_name'");
echo "<select name='colour' id='colour' style='font-family: Calibri;font-size: 10pt;'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = ''>" . $row['colour'] . "</option>";
}
echo "</select>";
mysql_free_result($result);
//Closes specified connection
?>
form2.php
<?php
//connection
$fruit_name = $_POST['fruit_name'];
$colour = $_POST['colour'];
?>
<label>
<input type="text" name="fruit_name" id="fruit_name" value = "<?php echo $fruit_name;?>" readonly>
</label>
<p>
<label>
<input type="text" name="colour" id="colour" value="<?php echo $colour;?>" readonly>
</label>
</p>
I usually don't do this but since I've some spare time on hand right now, I'm going to give the general approach that you can follow:
Include the following between your <head> tag.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
Below that, paste this code
<script type="text/javascript">
$(function(){
$('select#fruit_name').change(function(){
var selectedVal = $(this).val(); // get the selected value
$.ajax({ // send ajax request to the php file to process data
type:'post',
url:'php-page-name.php',
data:{'value':selectedVal},
success:function(ret) // display the result from php-page-name.php page
{
$('div#result').html(ret);
}
});
});
});
</script>
Lets move on to your HTML now
<select name="fruit_name" id="fruit_name" style="font-family: Calibri;font-size: 10pt;">
<option value="0">-- please choose --</option>
<option value="Pineapple">Pineapple</option>
<option value="Apple">Apple</option>
</select>
<div id="result">
<select>
<option>Select One</option>
</select>
</div>
php-page-name.php page (Do not forget to create this page and put it in the same folder as form1.php)
<?php
// put the code to connect to your database here
$fruit_name = $_POST['value']; // this will contain the value selected from first dropdown
$result = mysql_query("SELECT colour FROM fruit WHERE fruit_name = '$fruit_name'");
echo "<select name='colour' id='colour' style='font-family: Calibri;font-size: 10pt;'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row['colour']."'>" . $row['colour'] . "</option>";
}
echo "</select>";
mysql_free_result($result);
?>
PS : I'm using the mysql_* functions in this example since I'm assuming you're too. But this is not recommended as they are going to be deprecated soon. You might want to switch to mysqli or PDO

How to Auto Save Selection in ComboBox into MYSQL in PHP without submit button?

I have no experience with jquery and ajax, so far I just looking for source and edit paste the code into my coding. Now I try to look for tutorial autosave combobox selection but i fail to find it.Can someone help me? I only done with MYSQL display record, but I do not know how to auto update combobox selection nito MYSQL using jquery. Example, I want to select booking status, when i choose approve from combobox, it will automatically save into MYSQL without click button submit.
<?php
include('config.php');
$per_page = 9;
if($_GET)
{
$page=$_GET['page'];
}
//get table contents
$start = ($page-1)*$per_page;
$sql = "SELECT bookingID,eventinfo.eventTitle,boothAlias,testbook.bstatus,date, testbook.username, customer.companyName, customer.contactName from eventinfo, testbook, customer where testbook.username=customer.username AND testbook.eventID=eventinfo.eventID order by date desc limit $start,$per_page";
$rsd = mysql_query($sql);
?>
<form method="post" name="form">
<table width="800px">
<?php
//Print the contents
while($row = mysql_fetch_array($rsd))
{
$id=$row['companyName'];
$contactName=$row['contactName'];
$eventTitle=$row['eventTitle'];
$date=$row['date'];
$status=$row['bstatus'];
$booth=$row['boothAlias']
?>
<tr><td style="color:#B2b2b2; padding-left:4px"><?php echo $id; ?></td><td><?php echo $contactName; ?></td>
<td><?php echo $eventTitle; ?></td><td><?php echo $booth; ?></td><td><?php echo $date; ?></td><td><select name='status' id='status'>
<option value='-1'>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select></td>
</tr>
<?php
}
?>
</table>
</form>
image
do this
<select name='status' id='status'>
<option value=''>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select>
<div id="autosavenotify"></div>
<script>
$(document).ready(function(){
$('select').live('change',function () {
var statusVal = $(this).val();
alert(statusVal);
$.ajax({
type: "POST",
url: "saveStatus.php",
data: {statusType : statusVal },
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
on saveStatus.php do your mysql update
<?php
$st=$_POST['statusType'];
$qry =" UPDATE tableName SET `tablefield`=$st .. ";
$done = mysql_query($qry);
if($done)
{
echo "Saved Successfully";
}
?>
my first guess would be to use onChange event in select element, eg. <select name='status' id='status' onChange='updateMySQL();'>
in updateMySQL() you could call external script to save data into database. I'm not sure hot to achieve it though, it's just a guess. good luck in finding solution!

Categories