php + populate drop down menu on the selection of another - php

i am creating three drop down menu and it work very good but i want that the second drop list appear on the selection of the first one and the third on the selection of the second one how to do that if any one can guide me or give me an example i will appreciate that
PS: the second drop list or table have a foreign key from the first one so here i want to work to populate the second based on the selection of the first.
fun.inc.php
<?php
require_once('db.inc.php');
function connect(){
mysql_connect(DB_Host, DB_User ,DB_Pass )or die("could not connect to the database" .mysql_error());
mysql_select_db(DB_Name)or die("could not select database");
}
function close(){
mysql_close();
}
function countryQuery(){
$countryData = mysql_query("SELECT * FROM country");
while($record = mysql_fetch_array($countryData)){
echo'<option value="' . $record['country_name'] . '">' . $record['country_name'] . '</option>';
}
}
function specializationQuery(){
$specData = mysql_query("SELECT * FROM specialization");
while($recordJob = mysql_fetch_array($specData)){
echo'<option value="' . $recordJob['specialization_name'] . '">' . $recordJob['specialization_name'] . '</option>';
}
}
function governorateQuery(){
$goverData = mysql_query("SELECT * FROM governorate");
while($recordGover = mysql_fetch_array($goverData)){
echo'<option value="' . $recordGover['governorate_name'] . '">' . $recordGover['governorate_name'] . '</option>';
}
}
?>
index.php
<?php
require_once('func.inc.php');
connect();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>testDroplistdown</title>
</head>
<body>
<p align="center">
<select name="dropdown">
<?php countryQuery(); ?>
</select>
</p>
<br />
<br />
<p align="center">
<select name="dropdown2">
<?php governorateQuery(); ?>
</select>
</p>
<p align="left">
<select name="dropdown3">
<?php specializationQuery(); ?>
</select>
<?php close(); ?>
</p>
</body>
</html>

make sure u never leave a after your php closing tag and the begging of your html header, it can trow some nasty errors
this script should work
<?php
require_once('func.inc.php');
connect();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>testDroplistdown</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p align="center">
<div id="dropdown1div"><select id="dropdown1" name="dropdown">
<?php countryQuery(); ?>
</select></div>
</p>
<br />
<br />
<p align="center">
<div id="dropdown2div"></div>
</p>
<p align="left">
<div id="dropdown3div"></div>
<script type="text/javascript">
$("#dropdown").change(function() {
val = $(this).val();
var html = $.ajax({
url: "dropdown_select.php?dropdown=2&val="+val+"",
async: true,
success: function(data) {
$('#dropdown2div').html(data);
}////////////function html////////
})/////////function ajax//////////
});
</script>
<?php close(); ?>
</p>
</body>
</html>
dropdown_select.php
<?php
require_once('func.inc.php');
connect();
if(isset($_GET['val'])){
$val = $_GET['val'];
$dropdown = $_GET['dropdown'];
}
if($dropdown == '2'){
echo '<select id="dropdown2" name="dropdown2">';
governorateQuery();
echo '</select>';
?>
<script type="text/javascript">
$("#dropdown2").change(function() {
val = $(this).val();
var html = $.ajax({
url: "dropdown_select.php?dropdown=3&val="+val+"",
async: true,
success: function(data) {
$('#dropdown3div').html(data);
}////////////function html////////
})/////////function ajax//////////
});
</script>
} // end if statement
if($dropdown == '3'){
echo '<select id="dropdown3" name="dropdown3">';
specializationQuery();
echo '</select>';
} // end if statement
close();
?>

You can't do that with PHP only, you need to use AJAX.
Ajax is a technique using javascript and PHP to load new results according to user input.
Let's say you select a country and you get a new select box with all the cities FROM that country.
You'll have to create an event handler to the first select box:
<select name="dropdown" onchange="loadNewSelectBox(this.value)">
// values
</select>
The loadNewSelectBox would be an function that would post a new xmlhttp request to a php file on your server with the value of your select box. Then you would echo data from that PHP file (json, xml, html..) with response. Your response (for beginner) would probably be html containing the new select box. Then you would append that response to a div or paragraph.
This is an example similar to your task : http://www.w3schools.com/php/php_ajax_database.asp
And this is a good learning source.
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

Related

Return php value from ComboBox

i create a combobox with sql values but how i know what the value selected?
this is my code, have a lot of scrap but is my tests :)
I link to send the selected option to another php file already created.
<?php
require_once('auth.php');
require_once('config.php');
require_once('no-cache-headers.php');
require_once('functions.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Nova Mensagem</title>
<link href="Formatacao.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Bem-vindo <?php echo $_SESSION['USERNAME'];?></h1>
<form id="regForm" name="regForm" method="post" action="verificarMensagem.php">
<table width="300" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<?php
mysql_connect('localhost','comunicat','comunicat');
mysql_select_db('Comunicat');
$iduser =$_SESSION['SESS_MEMBER_ID'];
$query="Select * from Usuarios where id <> '$iduser'";
$resultado=mysql_query($query);
echo '<select name=”Nome”>';
while($linha=mysql_fetch_array($resultado))
{
echo '<option value="' . $linha['ID'] . '">' . $linha['Nome'] . '</option>';
}
echo '</select>';
?>
<textarea rows="4" cols="50" name="mensagem" id="mensagem">
</textarea>
<td> </td>
<td><input type="submit" name="Submit" value="Enviar" /></td>
</tr>
</table>
</form>
</body>
</html>
You can get value of select element in php by using $_POST[name-of-element]:
<?php
echo $_POST['Nome'];
?>
That works also with checkboxs,radios,etc
When the form that contains your "combobox" is submitted, you can get the selected value from your combobox with the line of code below:
$val = $_POST['Nome']; // if the form was submitted using post method
$val = $_GET['Nome']; // if the form was submitted using get method
NB
Do not use mysql_* no more, it is officially deprecated. Use mysqli or PDO instead.

dynamic select list in php with mysql

using select list with mysql created a list. I have a mysql data with c_code,Table center,and having data 1. id,2. name,3. code. i want to select name from mysql data after selecting name in data list want to show the code crosponding that name without using any submit button from select dropdown list, and the code shows in either label or in inputtext box.
Here is my full code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 1</title
</head>
<body>
<form id="form1" name="form1" action="" , method="post" >
<div>
<label for="list">Center</label>
<select name="list">
<option value=''>-----SELECT-----</option>
<?php
$conn = mysqli_connect('localhost', 'root', '');
$result = mysqli_query($conn, 'SELECT id,name,code FROM center');
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='$row[id]'>$row[name]</option>";
}
?>
</select>
</div>
</form>
</body>
</html>
First, let's organize the code a bit...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 1</title>
</head>
<body>
<form id="form1" name="form1" action="" method="post">
<div>
<label for="list">Center</label>
<select name="list">
<option value=''>-----SELECT-----</option>
<?php
$conn=mysqli_connect('localhost','root','');
$result=mysqli_query($conn,'SELECT id,name,code FROM center');
while($row=mysqli_fetch_assoc($result)) {
echo "<option value='$row[id]'>$row[name]</option>";
}
?>
</select>
</div>
</form>
</body>
</html>
Second, dynamically doing anything in HTML is impossible with PHP, PHP is a server-side script and can not post back data after user manipulations without refreshing the page.
You are looking for an $.ajax(); solution. I'd suggest looking into it on http://api.jquery.com/jQuery.ajax/
Good luck!
you should write select tag out of form
because this list will not populated until form submitting
Hope its this what you need. you do a select on the id and name for the dropdown menu. after you selected an element the form ll be submitted and a new sql query ll return you the code. there are several other ways to return the code, this is just one easy way
notice, i didnt use prepared statements! because i do not have the correct synatx in head right now... you should think about a general implementation of prepared statements.
<form id="form1" name="form1" action="" method="post" >
<div>
<label for="list">Center</label>
<select name="list" onchange="this.form.submit()">
<option value=''>-----SELECT-----</option>
<?php
$conn = mysqli_connect('localhost', 'root', '');
$result = mysqli_query($conn, 'SELECT id,name FROM center');
while ($row = mysqli_fetch_assoc($result))
{
$selected = (isset($_POST['list']) && $_POST['list'] == $row['id']) ? 'selected' : '';
echo "<option value='$row[id]' $selected >$row[name]</option>";
}
?>
</select>
</div>
<div>
<?php
if (isset($_POST['list']))
{
$result = mysqli_query($conn, 'SELECT code FROM center WHERE id=' . $_POST['list']);
while ($row = mysqli_fetch_assoc($result))
{
echo $row['code'];
}
}
?>
</div>
</form>
Try to echo $row variables separately by concatenation.
So change this line
echo "<option value='$row[id]'>$row[name]</option>"
to
echo "<option value=". $row[id] .">".$row[name]."</option>"
or you can use escape character like this
echo "<option value={$row[id]}>{$row[name]}</option>"
I think now your select option would work.
If I understand you right, you're trying to do the same thing I was before I discovered this solution...
I was creating a dropdown for selecting how many results to show per page.
Total of 6 options, which I stored in an array...
$page_sizes = array(10, 25, 50, 100, 200, 500);
Next, I used a "foreach" to build the options list...and an if statement to show the option as selected ONLY if it matched the current page size (page size was determined earlier in the script using the $page_size variable)...
foreach($page_sizes as $pagesize_opt){
($pagesize_opt == $page_size) ? $pagesize_options .= '<option selected="selected" value="'.$pagesize_opt.'">'.$pagesize_opt.'</option>':
$pagesize_options .= '<option value="'.$pagesize_opt.'">'.$pagesize_opt.'</option>';
}
Then, I inserted my options into my drop down...
$page_size_select = '<strong>Results Per Page </strong><select id="analytics_page_size_select">'.$pagesize_options.'</select>';
You could do the same using a "while" iterator. Just check to see if the array element matches your selected element.
OR, if you want to get fancy and use an associative array which selects the option by the key instead of by the value, you can use the "key()" function to get the key and test whether it matches your selected key...
http://php.net/manual/en/function.key.php
So the entire code looks like this...
$page_sizes = array(10, 25, 50, 100, 200, 500);
foreach($page_sizes as $pagesize_opt){($pagesize_opt == $page_size) ? $pagesize_options .= '<option selected="selected" value="'.$pagesize_opt.'">'.$pagesize_opt.'</option>':
$pagesize_options .= '<option value="'.$pagesize_opt.'">'.$pagesize_opt.'</option>';
}
$page_size_select = 'Results Per Page '.$pagesize_options.'';

Click Button To Fill Listbox

I am trying to fill a listbox on a webpage and I want the listbox to start blank. Once the button is clicked the listbox should populate. My code below automatically fills the listbox but I would rather have the button do it.
<?php
$dbc = mysql_connect('','','')
or die('Error connecting to MySQL server.');
mysql_select_db('MyDB');
$result = mysql_query("select * from tblRestaurants order by RestName ASC");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SEARCH</title>
</head>
<body>
<form method="post" action="1004mcout.php">
<p><center>SEARCH</CENTER></P>
<select name="RestName">
<?php
while ($nt= mysql_fetch_assoc($result))
{
echo '<option value="' . $nt['RestID'] . '">' . $nt['RestName'] . '</option>';
}
?>
</select>
<p> SPACE</p>
<p>Click "SUBMIT" to display the calculation results</p>
<input type="submit" name="Submit" value="Submit" />
<br />
</form>
</body>
</html>
I would either: Preload the data into the page as some ready but invisible html list (maybe a bit n00b), or save the data as a javascript array and a function will load it into the page (better), or do an ajax call to the same page (for simplicity) (probably best, leaves you the option open for updated data after page initiation).
The Ajax route will have to use jQuery (change this_page.php to whichever page this is called):
<?php
while ($nt= mysql_fetch_assoc($result))
$arrData[] = $nt;
//If you want to test without DB, uncomment this, and comment previous
/*$arrData = array(
array('RestID' => "1", 'RestName' => "Mike"),
array('RestID' => "2", 'RestName' => "Sebastian"),
array('RestID' => "3", 'RestName' => "Shitter")
);*/
if(isset($_GET["ajax"]))
{
echo json_encode($arrData);
die();
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function displayItems()
{
$.getJSON("this_page.php?ajax=true", function(data) {
$.each(data, function(index, objRecord) {
var option=document.createElement("option");
option.value=objRecord.RestID;
option.text=objRecord.RestName;
$("#RestName").append('<option value="' + objRecord.RestID + '">' + objRecord.RestName + '</option>');
});
});
}
</script>
<title>SEARCH</title>
</head>
<body>
<form method="post" action="1004mcout.php">
<p><center>SEARCH</CENTER></P>
<select id="RestName"></select>
<p> SPACE</p>
<p>Click "SUBMIT" to display the calculation results</p>
<button type="button" onclick="javascript:displayItems();">Insert options</button>
<br />
</form>
</body>
</html>
Essentially, what it does, it collects the data, checks if there is a request for the ajax data in the url, if not, it prints the rest of the page (with an empty select). If there is an ajax flag in the url, then the php will encode the data into json, print that and stop.
When the User receives the page with an empty select, it clicks the button which will trigger the displayItems() function. Inside that function, it does a jQuery-based ajax call to the same page with the ajax flag set in the url, and the result (which is json), is evaluated to a valid javascript array. That array is then created into options and loaded into the RestName SELECT element.
A final cookie? You could just print the data as options, into the select anyway, just like the previous answers described. Then, inside the displayItems() function, you clear the select before loading it from the jQuery/ajax call. That way, the user will see data right from the beginning, and will only update this with the most recent data from the DB. Clean and all in one page.
<?php
$dbc = mysql_connect('','','')
or die('Error connecting to MySQL server.');
mysql_select_db('MyDB');
$result = mysql_query("select * from tblRestaurants order by RestName ASC");
?>
<html>
<head>
<script>
function displayResult()
{
var x =document.getElementById("RestName");
var option;
<?php
while ($nt= mysql_fetch_assoc($result))
{
echo 'option=document.createElement("option");' .
'option.value=' . $nt['RestID'] . ';' .
'option.text=' . $nt['RestName'] . ';' .
'x.add(option,null);';
}
?>
}
</script>
</head>
<body>
<select name="RestName">
</select>
<button type="button" onclick="displayResult()">Insert options</button>
</body>
</html>
Read more about adding options to select element from java script here
how about this simple way,
is this what you mean,
its not safe, any one can post show=yes but i think you just like users to be able to simply click and see result
<select name="RestName">
<?php
// if show=yes
if ($_POST['show'] == "yes"){
$dbc = mysql_connect('','','')
or die('Error connecting to MySQL server.');
mysql_select_db('MyDB');
$result = mysql_query("select * from tblRestaurants order by RestName ASC");
while ($nt= mysql_fetch_assoc($result))
{
echo '<option value="' . $nt['RestID'] . '">' . $nt['RestName'] . '</option>';
}
}
?>
</select>
<form method="post" action="#">
<input type="hidden" name="show" value="yes" />
<input type="submit" name="Submit" value="Submit" />
</form>
you can also simply use a hidden div to hid listbox and give the button an onclick action to show div, learn how in here: https://stackoverflow.com/a/10859950/1549838

Updating form fields based on drop down menu selection using AJAX and PHP

I've found tutorials to update form elements with set data and also to show table based on the drop down selection. BUT, I still can't figure out how to merge these two things together.
As it says in the title - I need to update form fields based on the selection from drop down menu.
So far, I've came to this:
HTML:
<html>
<head profile="http://www.w3.org/2005/20/profile">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
<script>
function showUser(str)
{
var strURL="getUser2.php?user="+str;
http('GET', strURL, ajax_response, document.form1);
}
function ajax_response(data) {
for(var key in data) {
document.form1[key].value = data[key];
}
}
</script>
</head>
<body>
<div style="margin:30px 500px">
<form name="form1">
<select name="users" onchange="ajax_request()" value="showUser(this.value)">
<option value="">new</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
<br />
<br />
ID <input type="text" id="ID"><br>
name <input type="text" id="name"><br>
city <input type="text" id="city"><br>
</form>
</div>
</body>
</html>
PHP:
<?php
$user=$_GET["user"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("pophelper", $con);
$sql="SELECT * FROM phonebook WHERE ID = '".$user."'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$ID=$row['ID'];
$names=$row['names'];
$city=$row['city'];
require_once "json/JSON.php";
$json = new Services_JSON();
$value = array("ID" => $ID, "names" => $names, "city" => $city);
$output = $json->encode($value);
print($output);
mysql_close($con);
?>
I've tried separately to run PHP file, and it gave the correct result. But when I run it from html, fields just remain empty no matter which option I choose.
Did I miss something? Thank you in advance.

JavaScript enable button not working in php

I have used Javascript to enable or disable a button, depending on the input value. I'm new to PHP, so I don't know why this isn't working. Here's the PHP code:
<?php
session_start();
include_once('header.php');
include_once('functions.php');
$_SESSION['userid'] = 1;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Microblogging Application</title>
</head>
vbody>
<?php
if (isset($_SESSION['message'])){
echo "<b>". $_SESSION['message']."</b>";
unset($_SESSION['message']);
}
?>
<form method='post' action='add.php'>
<p>Your status:</p>
<textarea name='body' rows='5' cols='40' wrap=VIRTUAL></textarea>
<input type="text" name="age" />
<input type="text" name="poscode" />
<input type="submit" name="submit" value="Post" disabled="disabled"/>
</form>
<script type="text/javascript">
$('input[name="age"], input[name="poscode"]').change(function(){
if ($(this).val())
{
$("input[name='submit']").removeAttr('disabled');
}
});
</script>
<?php
$posts = show_posts($_SESSION['userid']);
if (count($posts)){
?>
<table border='1' cellspacing='0' cellpadding='5' width='500'>
<?php
foreach ($posts as $key => $list){
echo "<tr valign='top'>\n";
echo "<td>".$list['body'] ."<br/>\n";
echo "<small>".$list['stamp'] ."</small></td>\n";
echo "</tr>\n";
}
?>
</table>
<?php
}else{
?>
<p><b>You haven't posted anything yet!</b></p>
<?php
}
?>
</body>
</html>
How do I change it so when the value of the input = "foo", the button is now clickable.
Thanks in advance
-Ben
I can't make sense of your question, but if you're asking what I think you're asking (which is "how do I enable the button if the form is populated on page load?"), change your script to the following:
$.ready(function(){
$('input[name="age"], input[name="poscode"]').change(function(){
if ($(this).val())
{
$("input[name='submit']").removeAttr('disabled');
}
}).change();
});
I added the change call to trigger the change event handler, and wrapped it in jQuery's ready handler.
Try using the attr function like below
$('#element').attr('disabled', true);
Or
$('#element').attr('disabled', false);
Because different browsers treat the disbaled attribute differently, using true and false lets jquery handle the cross browser issues

Categories