Multiple, dynamic dropdown list based on user selection - php

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

Related

Dependent Drop Down lists in PHP and HTML

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.

Dynamicly populate field after getting value from dropdown

I have a form that uses a dropdown menu to select an option. After the option is selected I want to get a value form my DB to populate the next field with the correspondent value (in the scenario is to get the square footage of a rental property - but this value can be edited)
This is the field where i have the options:
<div>
<label class="control-label " for="local">Local</label>
<select class="select form-control" id="local" name="local" ><?php echo $lista_fraccoes;?></select>
</div>
after this i have the script to get the data:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$('#local').on('change', function(){
var .local = this.value;
$.ajax({
type: "POST",
url: "area_fraccao.php",
data:'local='+local,
success: function(result){
$("#area").value(result);
}
});
});
</script>
And after this i have the field that i want to populate:
<div class="form-group m-2 ">
<label class="control-label " for="area" type="value">Area</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fas fa-ruler-combined"></i>
</i>
</div>
<input class="form-control" id="area" name="area" placeholder="Em m2" type="value" value=""/>
</div>
In the area_fraccao.php file is where i get the correspondent value:
require_once 'config.php';
require_once 'functions.php';
$local = $_GET['local'];
$query_area = "SELECT * FROM TbFraccao WHERE PkFraccao=" . $local;
$result_area = mysqli_query($link, $query_area);
while ($row_area = mysqli_fetch_assoc($result_area)){
$area = $row_area['FraccaoArea'];
echo $area;
};
The solution I'm Using is presenting the following errors in web inspector
The code I'm using is updated matching the given suggestions.
Looking at your code, The code seems Ok. Please make sure that the query has no error by checking if running query was successful, check there is atleast one result and remove the semi-colon after while closing bracket.
if($result_area = mysqli_query($link, $query_area)){//the query is Ok
if(mysqli_num_rows($result_area)>0){//check there is atleast one result
while ($row_area = mysqli_fetch_assoc($result_area)){
$area = $row_area['FraccaoArea'];
echo $area;
}
}
}
else{//you have an error when writing your query
echo 'Wrong query';
}
if that does not help, the problem might be you did not sanitize the data during saving and there are characters from that data that interferes with the query. Show us how you did filtering before saving the data.
Set value of input elements using value method of jQuery
$("#area").value(result);
html() method is used to set innerHTML of elements

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.

my websites search results are immune to jquery

I have a website where I can search for things in the database, let it be boats for now.
I use this form
<form method="post" action="">
<input type="text" class="form-control" id="searchField" name="searchField" autocomplete="off"/>
</form>
<div id="searchResults"></div>
And this jquery to display serch results
//Autocomplete search field
$("#searchField").keyup(function(){
var input = $("#searchField").val();
$("#searchResults").html("");
input = $.trim(input);
if(input){
$.post( "source/pages/processing/search_boats.php", {inputString:""+input+""}, function( data ) {
$( "#searchResults" ).html( data );
});
}
});
the search_boats.php look like this:
<?php
$input = $_POST['inputString'];
$sql = mysqli_query($dbcon, "SELECT boat_name FROM boats WHERE boat_name LIKE '%".$input."%' ORDER BY boat_name LIMIT 5 ");
echo "<ul id='searchUL'>";
while($row = $sql -> fetch_array()){
?>
<div class="row">
<div class="col-md-4">
<? echo $row['boat_name']?>
</div>
</div>
<?
For now this working perfectly - just like I want it. However, when these search results appear on the website I can not add any click events on them. Ive tried making buttons, anchors. I suspect jquery is not ready for this added piece of search results that Im displaing the user. For example, I'm able to hide a div called myDiv on click on any anchor tags
like so..
$("a").click(function(){
$("#myDiv").toggle();
});
but when I click anchors on the search results, the myDiv isn't being hidden.
What could be the problem ?
Try This
$('body').on('click','a',function(){
$("#myDiv").toggle();
});

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