Dependent Drop Down lists in PHP and HTML - php

I tried to implement a dependent drop down lists system. The code in contact.php page is:
<?php
$link = new mysqli("localhost", "root", "", "graphicdesign");
if($link->connect_error){
die("ERROR: Nu s-a putut realiza conexiunea la baza de date " .$link->connect_error);
}
$resultSet = $link->query("SELECT * FROM orase") or die('Error In Session');
/* $rowsn = mysqli_fetch_array($resultSet);
$n_oras=$rowsn['denumire_oras'];
$id_orasss=$rowsn['id_oras']; */
//$resultSetRep = $link->query("SELECT id_oras, denumire_rep FROM reprezentante where id_oras='$id_oras'") or die('Error In Session');
//$rows1= mysqli_fetch_array($resultSetRep);
?>
<!DOCTYPE HTML>
<html>
<head>
--head info
</head>
<body>
<form action="#">
<div class="row form-group">
<div class="col-md-12">
<label style="margin-right:15px;">Oras</label>
<select id="denum_oras" name="den_oras">
<?php
while($rows = mysqli_fetch_array($resultSet)) {
$n_oras=$rows['denumire_oras'];
$id_oras=$rows['id_oras'];
echo "<option value='$id_oras'>$n_oras</option>";
}
?>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label style="margin-right:15px;">Reprezentanta</label>
<select id="reprez" name="reprez">
<?php
while($rows2=$resultSet->fetch_assoc()) {
$id_oras=$rows2['id_oras'];
$den_rep=$rows2['denumire_rep'];
$resultSetRep = $link->query("SELECT id_oras, denumire_rep FROM reprezentante where id_oras='$id_oras'") or die('Error In Session');
while($rows3=$resultSetRep->fetch_assoc()) {
$id_rep = $rows3['id_rep'];
$den_rep = $rows3 ['denumire_rep'];
echo "<option value='$id_rep'>$den_rep</option>";
}
}
?>
</select>
</div>
</div>
</form>
</body>
</html>
The first drop down list is working, it is retrieving the right data from table "orase" in the database:
But for the second drop down, i want that, when i select the option "Braila" form the first drop down, to show the values from the database with the foreign key "id_oras" as the selected choice.
In this case, when I select "Braila" from the first drop down list, with the id_oras=1 in the table orase, I want that the second drop down list to retrieve data from the table "reprezentante" where id_oras = 1, in this case to retrieve values "Rep Braila" and "Rep Braila 2" to be shown in the drop down, but this is not happening..
This is a capture of the page:
The code i posted is the best one i thought about, but still doesn't work.. please help me!
Thanks!

PHP is preprocessor language isn't compile on runtime you can use Ajax or XMLHttpRequest to get the data. After that, you can use Jquery or javascript to bind the data in the select box

You need to use Ajax for accomplishing this task. Using onChange jquery event when parent dropdown value gets changed will populate child or dependent dropdown accordingly.
Please refer this link: Populate a dropdown list based on selection of another dropdown list using ajax
Hope this helps.

As others have mentioned you will need to inject a little bit of Javascript into your code.
Your first Select looks fine, but the second would have to be re-written.
Put an onchange event into your first select like so:
<select name="list" id="list" onchange="update(this)">
And a Div to hold your second dropdown list.
<div id="secondlist">
// contents of returned html from "getsecondlist.php" will go here
</div>
Then put the following Javascript inbetween your head tags.
This will call "getsecondlist.php" and pass a parameter of idoras.
"getsecondlist.php" will return the second dropdown list, which is stored in this.responseText.
<script>
function update(e) {
idoras = e.options[e.selectedIndex].value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("secondlist").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getsecondlist.php?idoras=" + idoras, true);
xhttp.send();
}
</script>
getsecondlist.php
<div class="row form-group">
<div class="col-md-12">
<label style="margin-right:15px;">Reprezentanta</label>
<select id="reprez" name="reprez">
<?php
$id_oras=$_GET['idoras'];
$resultSetRep = $link->query("SELECT id_oras, denumire_rep FROM reprezentante where id_oras='$id_oras'") or die('Error In Session');
while($rows3=$resultSetRep->fetch_assoc()) {
$id_rep = $rows3['id_rep'];
$den_rep = $rows3 ['denumire_rep'];
echo "<option value='$id_rep'>$den_rep</option>";
}
?>
</select>
</div>
</div>
The $_GET['idoras'] gets the parameter sent in from the Javascript call.
Hope this helps.

Related

Show price from DB

The user goes change the nm_peca, will select tipo_preco and then find the price in MySQL database to complete the textbox vlr_peca.
What do I need to do to get the value of products?
<?php>
$query = mysql_query("SELECT id, nm_peca, vlr_original,
vlr_paralelo, fabricante
FROM peca
ORDER BY nm_peca");
<select id="nm_peca" name="nm_peca"
title="Selecione um status."
class="form-control" size="1">
<option value="">Status</option>
<option value="N/A">N/A</option>
<option value="S">S - Substituir</option>
</select>
</div>
</div>
<select id="tipo_preco" name="tipo_preco"
class="form-control" size="1">
<option value="">Tipo</option>
<option value="Peça Original">Original</option>
<option value="Peça Paralela">Paralela</option>
</select>
</div>
</div>
<div class="col-md-1">
<div class="input-group btn-group">
<input type="text" value="????????" name="vlr_peca"
class="form-control" readonly>
</div>
</div>
Well your code is a little confusing because what you really want is not clear to me, maybe it doesn't help that it's in a different language. What is the $query for? You are not using this in the code, so you'll need to do this to access it:
$rows = array();
while ($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
print '<pre>'. print_r($rows, true) . '</pre>';
Then you'll need to use an ajax request OR setup javascript vars on the front end to make changes. I'm just going to go ahead and use the latter since it's more illustrative.
So I would add the cdn of jQuery which is https://code.jquery.com/jquery-2.1.4.min.js to the top of your file in a tag like:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
Then you'll need to add an input id to that input tag like <input id="dynamic-variable" type="text" value="????????" name="vlr_peca"> and then use something like:
<script type="text/javascript">
$(document).ready(function() {
$('#tipo_preco').change(function() {
if ($(this).val() == 'Peça Original') {
$('#dynamic-variable').val('$5,000,000,000.00');
} else if ($(this).val() == 'Peça Paralela') {
$('#dynamic-variable').val('$300 billion trillion dollars');
} else {
$('#dynamic-variable').val('Bro. Choose one.');
}
});
});
</script>
I'm not going to program this whole thing for you since I don't know what kind of data you are getting from your DB, but this should be good enough to get you started. You need to be able to access the data in the mysql query, and you may just want to use the <?= $db_variable ?> or <?php echo $db_variable?> in your javascript where I have the amount variables. This should be good enough to get you started. Read up on php mysql_query and jQuery
AJAX
If you were to do this via AJAX, you would need a second page that accesses the database, you'd have to $_GET or $_POST variables and then print back the amount.
So your JavaScript would be something like this:
$.get('/the/page.php?tipo_preco=' + $('#tipo_preco').val(), function(response) {
if (response != '') {
$('#dynamic-variable').val(response);
}
});
And your second page would be something like this:
<?php
// code that sets up the database
// .... //
// now your code
$selected_value = $_GET['tipo_preco'];
$result = mysql_query("SELECT price FROM table WHERE column_val = '" . mysql_real_escape_string($selected_value) . "'");
$row = mysql_fetch_assoc($result); // assuming you're only fetching one row
print $row['price'];
?>
I would suggest you just go with the first suggestion, it's faster, less moving parts.

Run different query based on a dynamic HTML dropdown list

I made some PHP code to generate this page. I successfully get all the items from a column into a HTML dropdown list (it's a dynamic list). I want to write some code so that when user selects an item from the list and hit submit, it will take user to a new page contains corresponding information on it. I have no idea what kind of code would be included in. Please help. Thanks!
For instance, if user select 50A-1, it will populate a table has all the items located at 50A-1.
Two pieces of code I wrote, first is the page gives you the dropdown list and the submit button. The second is the result page, but it only shows the whole inventory so far, it doesn't have a way to connect to the dropdown list option.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Inventory</title>
</head>
<body>
<div>
<a>SQL Connection test</a>
<form action="connect.php" method="POST">
<div class="center">
<input type="submit" value="Connect to MySQL" />
</div>
</form>
</div>
<div>
<section>
<article>
<p>
<select name="dropdown">
<?php query() ?>
</select>
<?php close() ?>
</p>
</article>
</section>
<div>
<input type="submit" value="Submit" />
</div>
</div>
</body>
</html>
Second page
<?php
include_once 'db.inc.php';
// connect
function connect() {
// Connect to the MySQL server
mysql_connect(DB_HOST,DB_USER,DB_PASS) or die ('Could not connect to server!' . mysql_error());
mysql_select_db(DB_NAME);
}
// close
function close() {
mysql_close();
}
// query
function query() {
$myData = mysql_query("SELECT DISTINCT * FROM sheet0_100 GROUP BY location");
while($record = mysql_fetch_array($myData)) {
echo '<option value="' . $record['location'] . '">' . $record['location'] . '</option>';
}
}
?>
That's the purpose of HTML forms :)
You need to create a form to encapsulate that select:
<form action="process.php" method="get">
<select name="inventory_id">
<!-- Here all options -->
</select>
<button type="submit">See items</button>
</form>
Then in process.php you need to get the selected element and query the database, for example (I assume that you're using PDO):
<?php
$inventory_id = $_GET['inventory_id'] // The name attribute of the select
// Then you prepare the query
$query = "SELECT * FROM sheet0_100 WHERE id = :inventory_id";
// Execute the query and show the data...
use Sessions
example:
on your first page
session_start();
$_SESSION['your-dropdown-list-value'] = 'Root';
on your new page
//error_reporting(E_ALL);
session_start();
if(isset($_SESSION['your-dropdown-list-value'])) {
echo "Your dropdown selection " . $_SESSION['your-dropdown-list-value'];
}

Multiple, dynamic dropdown list based on user selection

I have read through all the "dynamic multiple dropdown lists" questions here on stackoverflow but could not find what I am looking for.
It's a form for states and cities. User select a state, through ajax I request the cities for that specific state ID.
But, I need to have the two selects already created and displayed (maybe the city select grayed out). An example here PenskeAutomotive.
What I managed to do so far is to have only the state select and upon the execution of ajax, from the XMLHttp.ResponseText to create the city select. An example here Dorpdown list example - at bottom of page.
I need to have both selects displayed and then only update the city select with the new values of the XMLHttp.ResponseText.
Can anybody point me to some direction?
UPDATE:
Right after posting I found a question that I have not read before. Went into it and I may have found my direction. I am just trying that right now. It's jQuery/Ajax. Question
Not sure where you're having trouble, but to (hopefully) point you in the right direction:
You could have both of your <select> elements created on the page, with the City dropdown having the HTML disabled attribute, which will gray it out.
The disabled dropdown will have no options, aside from maybe one that says something like "select state."
You'll add an onchange event listener to your State dropdown which will perform the AJAX call, and I would recommend you get your response back in JSON format.
Then you can clear out the options of the next dropdown and create and append the new options from your server, then enable the dropdown.
If you want to provide what you've done so far, I'm sure we can help debug it.
I use this code in my site, maybe is usefull for you:
in head:
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function(){
$("#select1").change(function(event){
var id = $("#select1").find(':selected').val();
$("#select2").load('../scripts/depto.php?id='+id);
});
});
</script>
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function(){
$("#select2").change(function(event){
var id = $("#select2").find(':selected').val();
$("#select3").load('../scripts/municipios.php?id='+id);
});
});
</script>
and in select:
<div class='control-group'>
<label class='control-label' for='typeahead'>País </label>
<div class="controls">
<select name="IDPAIS" id="select1" required>
<?
$sql = $conn->prepare("SELECT * FROM lista_paises");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion].'</option>';
}
?>
</select>
</div>
</div>
<div class='control-group'>
<label class='control-label' for='typeahead'>Departamento </label>
<div class="controls">
<select name="departamento" id="select2" required></select>
</div>
</div>
<div class='control-group'>
<label class='control-label' for='typeahead'>Municipio / Ciudad</label>
<div class='controls'>
<select name="ciudad" id="select3" required></select>
</div>
</div>
in the lista_paises.php
<?
include('../include/config.php');
$query = $conn->prepare("SELECT * FROM PAISES);
$respuesta="[";
foreach ($aMunicipios as $muni) {
$respuesta .="{id:".$muni["id_municipio"].",nombre_municipio:'".$muni["municipio_nombre"]."'},";
}
$respuesta = substr($respuesta,0,strlen($respuesta)-1);
$respuesta.="]";
echo $respuesta;
}
?>
in depto.php
<?
include('../include/config.php');
$sql = $conn->prepare("SELECT * FROM lista_estados WHERE relacion = ".$_GET['id']);
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion1].'</option>';
}
?>
in municipios.php(ciudad/city)
<?
include('../include/config.php');
$sql = $conn->prepare("SELECT * FROM MUNICIPIOS WHERE relacion1 = ".$_GET['id']);
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion2].'</option>';
}
?>
maybe works for you

How to add data to a combo with javaScript and then pick with POST?

I expose my case, I pick through mysql data and fill a combo with php and smarty, then I have a button to add more data to this combo and bbdd. Everything works correctly but me when POST data collecting that data added to the combo did not pick it up
CODE:
HTML code with smarty which fill the combo, and the button to add the new data to the combo
<form action="algo.php" method="post">
<div class="form-field">
<label for="cliente_sector">Sector*</label>
<select name="cliente_sector" id="cliente_sector">
{section name=sector loop=$sectores}
<option value="{$sectores[sector].sector}">{$sectores[sector].sector}</option>
{/section}
</select>
<p>Sector del cliente</p>
<label onclick="javascript:anadir('divAnadir')">Nuevo sector</label>
</div>
<div id="divAnadir" style="display: none;">
Nuevo sector:<input type="text" id="nuevo_sector" name="nuevo_sector" value=""/>
<input onclick="javascript:nuevoSector()" type="button" value="Añadir nuevo sector "/>
</div>
</form>
javascript functions
function anadir(a){
if(document.getElementById(a).style.display=="none")
$("#divAnadir").css("display", "block");
else
$("#divAnadir").css("display", "none");
}
function nuevoSector(){
var datos = document.getElementById("nuevo_sector").value;
$.get("/ajax/altaNuevoSector.php?sector="+datos, datos, function(data){
if(data != 1) {
alert('Nuevo sector añadido');
$("#divAnadir").css("display", "none");
$("#cliente_sector").append('<option value=" " selected="selected">'+data+'</option>')
return true;
}else{
alert('Este sector ya existe, pruebe de nuevo.');
return false;
}
});
}
Php script to update bbdd and response to javascript:
<?php
session_start();
require_once('../includes/config.php');
if($_GET['sector']){
$sql = "INSERT INTO clientes_sectores(sector) VALUES ('".$_GET['sector']."')";
$consulta = $con->ejecutar($sql);
if(!is_numeric($consulta))
echo '1';
else
echo $_GET['sector'];
}
?>
All work fine the data is added to the bbdd and displays in the combo, the problem is that the combo is in a form, by post I try to pick the data, if value cliente_sector is the new one not let me pick it up, the $ _POST ['cliente_sector'] is emptied. How do I fix it?
When i do submit in my form the $_POST['clientes_sector'] if in the combo is selected the new value.
thanks
Finally I refresh the page with a js function. Thanks for all.

Drop down list solution?

I am a newby so appologise for asking a basic question.
I have a php page - a 'create new project' page
There are some simple data such as name, deadline etc...
but depending on the type of the project I have 4 different ends (different pages?) in this FORM and I can't find the solution for it.
Here is my code:
<h1>New Project</h1>
<form name="newpr">
New project name:<input type="text" placeholder="new project name..."><br />
New project end date:<input type="text" placeholder="date..."><br />
New project type:
<select name="menu" onChange="location=document.newpr.menu.options[document.newpr.menu.selectedIndex].value;" >
<?php
$listdata = mysql_query("SELECT * FROM lists WHERE tag='prtype' ORDER BY listing ASC");
while($listresult = mysql_fetch_array($listdata))
{
if ($listresult["listing"]!="...") $link=$listresult["value"].".php";
else $link="";
echo "<option value='".$link."'>".$listresult["listing"]."</option> ";
}
?>
</select>
</form>
As you see the select list comes from Mysql and I would like a div under a form to be able to open page1.php or page2.php etc as user selects...
Thanks in advance
Andras
it might be ajax question...
I'd solve this the following way
<!-- using jQuery -->
<h1>New Project</h1>
<form method="" action="post">
New project name:<input type="text" placeholder="new project name..."><br/>
New project end date:<input type="text" placeholder="date..."><br/>
New project type:
<select name="menu">
<?php
$listdata = mysql_query("SELECT * FROM lists WHERE tag='prtype' ORDER BY listing ASC");
while($listresult = mysql_fetch_array($listdata))
{
$link = '';
if($listresult['listing'] != '...') {
$links = $listresult['value'] . ".php";
echo "<option value='$link'>${listresult['listing']}</option>";
}
}
?>
</select>
<div id="page">
<!-- container for loaded page -->
</div>
<script type="text/javascript">
$("select[name=menu]").change(function() {
var url = $("option:selected", this).val();
// Load a page to the container
$("#page").load(url);
});
</script>
</form>
Using jQuery I added on change handler on select box and if it's changed it loads via ajax a page to the div container.
And let me give you and advice - try to avoid mixing code and html. It leads to difficulties in further development and maintenance.
You want to make a HTTP request to your php page Checkout http://mootools.net/docs/core/Request/Request.HTML
http://mootools.net/docs/more/Request/Request.JSONP
Listen for the callback on your request then inject the returned data as an element into the DOM. Mootools is my weapon of choice but Jquery etc. all have this same functionality. call php page under Javascript function This question is very similar to yours.

Categories