Show options of selection from database based on parent selection - php

I have a form with 2 selection boxes, both of these boxes draw their options from my database through php.
The first one shows a list of books ordered by their ISBN like this:
<ISBN> - <Book name>
Now the second selection box will list all the editions that exist for the book selected in the previous selection (based on ISBN) and show each one of them with just the number of the edition.
What I do in this form is insert a specific copy of the selected book with the specific edition with its serial number in the database.
What I try to do is with the onChange to retrieve the ISBN selected from the first select and use it to show the options of the second selection.
I use the function dropdown() to display the book select and the dropdownEdition() for the edition select:
function dropdown($intIdField, $strNameField, $strTableName, $strOrderField,
$strNameOrdinal, $strMethod="asc") {
echo "<select name=\"$strNameOrdinal\">\n";
echo "<option value=\"NULL\">Select Value</option>\n";
$strQuery = "select $intIdField, $strNameField
from $strTableName
order by $strOrderField $strMethod";
$rsrcResult = mysql_query($strQuery);
while($arrayRow = mysql_fetch_assoc($rsrcResult)) {
$strA = $arrayRow["$intIdField"];
$strB = $arrayRow["$intIdField"] . " - " . $arrayRow["$strNameField"];
echo "<option value=\"$strA\">$strB</option>\n";
}
echo "</select>";
}
function dropdownEdition($intId1Field, $intId2Field, $strTableName, $strOrderField,
$strNameOrdinal, $strMethod="asc") {
echo "<select name=\"$strNameOrdinal\">\n";
echo "<option value=\"NULL\">Select Value</option>\n";
$strQuery = "SELECT $intId1Field, $intId2Field
FROM $strTableName
ORDER BY $strOrderField $strMethod";
$rsrcResult = mysql_query($strQuery);
while($arrayRow = mysql_fetch_assoc($rsrcResult)) {
$strA = $arrayRow["$intId1Field"];
echo "<option value=\"$strA\">$strA</option>\n";
}
echo "</select>";
}
What I basically want to do is pass the ISBN selected previously with the onChange, in the variable $intId2Field of the dropdownEdition().
The problem with that is I have searched for tutorials but I can't understand anything because I have never worked with jQuery or Javascript or AJAX and I am a very novice web programmer. That is the reason for I am asking for some help here.
Here are how the 2 functions are called:
<?php dropdown("book_ISBN", "book_title", "book", "book_ISBN", "book"); ?>
<?php dropdownEdition("edition_no", "???????", "edition", "edition_no", "edition"); ?>`
The ???? are the book_ISBN because I don't know how to pass it in.
Here are how the tables are connected:
References -

It sounds like you've already figured this out, but you will need to make an asynchronous request to the server, passing the ISBN to a PHP script which will execute your mySQL query.
Your PHP script would return the mysql results, possibly as a JSON object which could then be parsed using JS and formatted as HTML.
Here is some code I chucked together to demonstrate.
HTML:
<select name="isbn-select" id="isbn-select">
<option value="">Select an ISBN</option>
<option value="isbn1">isbn1</option>
<option value="isbn2">isbn2</option>
<option value="isbn3">isbn3</option>
</select>
JS:
$('#isbn-select').on('change', function() {
isbn = $('#isbn-select').val();
$.getJSON('get_editions.php',
{
isbn: isbn
},
function(data) {
var editions = [];
$.each(data, function(index, val) {
editions.push('<option value="' + val + '">' + val + '</option>');
});
$('<select/>', {
'id': 'editions-select',
'name': 'editions-select',
html: editions.join('')
}).appendTo('body');
});
});
PHP:
<?php
// Code to select editions from your database goes here....
// Your isbn can be accessed as $_GET['isbn']
$editions_arr = array('editon1', 'edition2', 'edition3');
echo json_encode($editions_arr);
?>
I have used jQuery's getJSON method to fetch a JSON object from get_editions.php. The results are then formatted as a select and appended to the HTML document. To keep things simple I am not doing any error checking or validation.
I hope this helps get you on the right track!
EDIT:
If you wish to return formatted HTML instead of a JSON object, here's how you can do that.
JS:
$('#isbn-select').on('change', function() {
isbn = $('#isbn-select').val();
$.get('get_editions.php',
{
isbn: isbn
},
function(data) {
$('body').append(data);
});
});
PHP:
<?php
// Code to select editions from your database goes here....
// Your isbn can be accessed as $_GET['isbn']
$editions_html = '<select id="editions-select" name="editions-select">';
$editions_html .= '<option value="edition1">edition1</option>';
$editions_html .= '<option value="edition2">edition2</option>';
$editions_html .= '<option value="edition3">edition3</option>';
$editions_html .= '</select>';
echo $editions_html;
?>
You can read up on jQuery's AJAX functions here: http://api.jquery.com/category/ajax/

Related

Get value from dropdown list to use in MySQL query

So I'm having this issue with geting a value from a dropdown list in HTML into a variable so that I can do the mysql query. This will be a little tricky to explain but I will do my best. (Do not be shy in correcting my english or my expressions so that the question becomes more concrete and easy to understand).
So I have this dropdown list that gets his values from a mysql query.
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
This "connects" with this query:
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'");
$result4 = mysql_query($sql4, $link);
This query will populate the dropdown list with values. What I'm seeking to do is to populate another dropdown list. For examples I select a list of countrys, and when I select on country it should appear all it's citys in the other dropdown list.
I have been searching guys. Belive me I have.
P.s: Please do not get mad if I change the question a couple of times when I see that you guys show me a way to explain it better. Sorry if my english isn't perfect. Thank you guys for the help.
You can do it with ajax and jquery. I try to write little example
<!-- index.php -->
<select name="desig_act" id="desig_act">
<?php while ($row2 = mysql_fetch_assoc($result4)): ?>
<option value="<?=$row2['new_name_freg']?>">
<?=$row2["new_name_freg"]?>
</option>
<?php endwhile; ?>
</select>
<!-- select tag for countries -->
<select name="country" id="country"></select>
write a little script to return countries as json
<?php //ajax-countries.php
$link = mysql_connect(); // connect as usual
$query = ("SELECT * FROM countries");
$result = mysql_query($query, $link);
$json = array();
while ($row = mysql_fetch_assoc($result)) $json[] = $row;
echo json_encode($json);
?>
Then you can have some sort of script like:
// script.js
$("#desig_act").change(function(){
$.getJSON( "ajax-countries.php", function( data ) {
$.each( data, function(key, val) {
$("#desig_act").append("<option val='" + key + "'>" + val + "</option>");
});
});
I hope it can be useful
1: Create a PHP script to return the data
Essentially just generate the value based off the $_GET input.
2: Create a json request in jquery
Calls the PHP file which will return the data and you will use that data to add more values to the select.
<?php
//Step 1 - The posted ajax data that will return our json request.
if(isset($_GET['fetchrow'])) //Is our ajax request called on page load? If yes, go to this code block
{
//Other stuff like DB connection
$pesq = mysql_escape_string($_GET['fetchrow']); //Put our variable as the variable sent through ajax
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'"); //Run our query
$result4 = mysql_query($sql4, $link); //Please change from mysql_* to mysqli
$data = array(); //The array in which the data is in
while($row = mysql_fetch_assoc($result4)) //Look through all rows
{
array_push($data, $row); //Put the data into the array
}
echo json_encode($data); //Send all the data to our ajax request in json format.
die; //Don't show any more of the page if ajax request.
}
?>
<html>
<head>
<script type='application/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js'></script> <!--Include jquery -->
<script>
//Step #2:
//The jquery script calls ajax request on change of the first select
$( "#desig_act" ).change(function() {
$.getJSON('thisfilename.php', {fetchrow:$("#desig_act").val()}, function(data){ //Get the json data from the script above
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) { //Loop through all results
html += '<option value="' + data[i].new_name_freg + '">' + data[i].new_name_freg + '</option>'; // Add data to string for each row
}
$('#otherselect').html(html); //Add data to the select.
});
});
</script>
</head>
<body>
<!-- Your html code -->
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
</td>
<!-- The new select -->
<select name='otherselect' id='otherselect'>
</select>
<!-- Rest of html code -->
</body>
</html>

Populating select box with neighborhoods of the selected city using AJAX

I'm all afternoon trying to run my code, but I'm doing something wrong. I will explain what I need to do.
I need to make when the user selects his city in a select box the neighborhoods corresponding to that city needs to be inserted into another select box. For this, I am using the following logic:
I have two tables in my database, one called cities and other called neighborhoods. The struct of the table cities is:
city_id (PRIMARY_KEY)
city_name
The struct of the table neighborhoods is:
neighborhood_id (PRIMARY_KEY)
city_id (To know what city the neighborhood belongs.)
neighborhood_name
Now in the register page I have this code to populate the user_city_id select box:
<label>City <span style='color: red'>*</span><br/>
<select id='user_city_id' name='user_city_id'>
<option value=''>-- Select a city --</option>
<?php
$sql = "SELECT * FROM cities ORDER BY city_id";
foreach($connection->query($sql) as $city)
{
echo "<option value='{$city['city_id']}'>{$city['city_name']}</option>";
}
?>
</select></label>
Ok, this code part insert the cities in select box with their ID in values and names. All right here.
Below I have the neighborhood select box with:
<label>Neighborhood <span style='color: red'>*</span><br/>
<select id='user_neighborhood_id' name='user_neighborhood_id'>
<option value=''>-- Select a neighborhood --</option>
</select></label>
Now is the hard part, the AJAX. I'm trying using jQuery and JSON to parse the data with the following code:
$(function(){
$('#user_city_id').change(function()
{
if($(this).val())
{
$.getJSON('neighborhood.ajax.php?search=', {city_id: $(this).val(), ajax: 'true'}, function(j)
{
var options = '<option value=""></option>';
for (var i = 0; i < j.length; i++)
{
options += '<option value="' + j[i].neighborhood_id + '">' + j[i].neighborhood_name + '</option>';
}
});
}
else
{
$('#user_neighborhood_id').html('<option value="">-- Select a neighborhood --</option>');
}
});});
The file to process the data is neighborhood.ajax.php. In this file I have:
require_once("db-connect.php");
$city_id = $_GET['user_city_id'];
$neighborhoods = array();
$sql = "SELECT * FROM neighborhoods WHERE city_id = {$city_id} ORDER BY neighborhood_name";
$stmt = $connection->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$neighborhoods[] = array
(
'neighborhood_id' => $neighborhood_id,
'neighborhood_name' => $neighborhood_name
);
}
echo(json_encode($neighborhoods));
...but simply nothing happens! Of course I'm doing something wrong, but so far I could not solve by myself. I'm trying and nothing.
I had never worked with AJAX. What is missing here?
You need to tell the browser that the data being sent from the server is JSON.
Add this line at the top of neighborhood.ajax.php
header('Content-Type: application/json');
I've found the solution today by myself.
It was a terribly simple solution that I could not see yesterday due to fatigue. I just noticed that I did not send the statement to insert HTML in select box, the options var data. I just inserted it with $('#user_neighborhood_id').html(options).show();. Here are the solution:
$(function(){
$('#user_city_id').change(function()
{
if($(this).val())
{
$.getJSON('neighborhood.ajax.php?search=', {city_id: $(this).val(), ajax: 'true'}, function(j)
{
var options = '<option value=""></option>';
for (var i = 0; i < j.length; i++)
{
options += '<option value="' + j[i].neighborhood_id + '">' + j[i].neighborhood_name + '</option>';
}
$('#user_neighborhood_id').html(options).show();
});
}
else
{
$('#user_neighborhood_id').html('<option value="">-- Select a neighborhood --</option>');
}
});});

select id from the select gender dropdown list

I have a dropdown list of gender. I am getting the values from my table 'candidate' and in this table i have a field which is actually a foreign key to another table.
The field is gender_code_cde, and the table name is gender_code. Now gender_code contains 2 rows. and id and a description. Its structure is like:
1->Male
2->Female
Its being displayed in dropdown list. but I want to get the id 1 if male is selected and id 2 if female is selected. My code is below:
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
I am working in codeIgniter.
// this will alert value of dropdown whenever it will change
<script>
function getvalue(val)
{
alert(val);
}
</script>
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER" id="Gender" onchange="getvalue(this.value)">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
In Javascript, you can get the value with native JS.
var e = document.getElementById("give-the-select-element-an-id");
var gender_cde = e.options[e.selectedIndex].value;
If, you want it back at the server, it will come in to PHP as $_GET['GENDER'] or $_POST['GENDER'] depending on if the form does a POST or a GET request.
If you are submitting a (POST) form and this is inside that form you can access the the value (id) from CodeIgniter's $_POST wrapper: $this->input->post('GENDER');. I don't use CodeIgniter so I could be wrong, but it will be located in your $_POST array from PHP.
If you just want to replicate the variable somewhere on the page you can just echo it. Or set via js/jQuery with document.getElementById('#something').value = value; or jQuery('#something').html(value);.
You should also change the following:
use a foreach in place of your while:
foreach ($query as $row) {
echo $row['gender_x'] . $row['gender_y'];
}
use the CodeIgniter SQL wrapper instead of depreciated PHP functions. The query part is $this->db->query('SELECT statement goes here');. You should look at your CodeIgniters' version documentation for a more in depth explanation.
EDIT: To make it a bit more clear, an example:
$query = $this->db->query('SELECT * FROM gender_code');
foreach ($query->result() as $row) {
echo '<option value="' . $row->gender_cde . '">' . $row->geneder_dsc . '</option>';
}
This is assuming you have setup the previous calls in CodeIgniter. Please see http://ellislab.com/codeigniter/user-guide/database/examples.html and you may wish to read http://ellislab.com/codeigniter/user-guide/

editing html using javascript that calls php function that gets information from sql database.. complicated...

i am trying to edit a select list every time the list before it is being changed.
what i am trying to do is change the list already existing into another list, called by a php function, that generates a list of the new information it has from the first list and an sql database.
it's pretty hard to explain so here is my code:
the base of my code
//php & html
....
$cli = lastNameList(); //first list
$tli = firstNameList(); //second list
echo"
$cli
<div id='editHtml'>$tli</div>
";
....
functions (php)
//the functions
function lastNameList(){
$options="<select id='lastNames'>";
$sql="SELECT * FROM lastName";
$result=mysql_query($sql);
$options.="<option value='blank'>-- last names --</option>" ;
while ($row=mysql_fetch_array($result)) {
$name=$row["name"];
$options.="<option value='$name'>$name</option>";
}
$options.= "</SELECT>";
return "$options";
}
function firstNameList(){
$options="<select id='firstNames' style='margin-right:40px;'>";
having a problem over here:
$sql="SELECT DISTINCT Name FROM firstName WHERE LastName ='lastNameSelectedGoesHere'";
//how do i get the value of the last name so i could make a query for it?
//using distinct to make sure there are no duplicates
$result=mysql_query($sql);
$options.="<option value='blank'>-- first name --</option>" ;
while ($row=mysql_fetch_array($result)) {
$name=$row["Name"];
$options.="<option value='$name'>$name</option>";
}
$options.= "</SELECT>";
return "$options";
}
js (inside a php file if it matters)
echo" <script type='text/javascript'>
$('#lastNames').change(function() {
document.getElementById('eTech').innerHTML=";
$ll = firstNameList();
echo"$ll;
});";
so as you can see my js file is in a php file, it does work, what i tried to do there, is generate a new first name list to come and replace the old one but i failed... anyone has an answer or suggestion to what i should do?
THis isn't complicated at all using ajax & jquery!
A quick dirty way is to do this
<div id="firstName"></div>
<script type='text/javascript'>
$('#lastNames').change(function() {
$('#firstName').load('getfirstname.php?lastname=' + $(this).val());
});
</script>
and for getfirstname.php page
$lastName = mysql_real_escape_string($_GET['lastname']);
$sql="SELECT DISTINCT Name FROM firstName WHERE LastName ='$lastName'";
//using distinct to make sure there are no duplicates
$result=mysql_query($sql);
$options="<select id='firstNames' style='margin-right:40px;'>";
$options.="<option value='blank'>-- first name --</option>" ;
while ($row=mysql_fetch_array($result)) {
$name=$row["Name"];
$options.="<option value='$name'>$name</option>";
}
$options.= "</SELECT>";
echo $options;
Here is a very simple page that shows how to execute php code using ajax and jquery.
<?
if(!isset($_GET['value'])):?>
<script src="jquery-1.7.1.js"></script>
<select id="select" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</options>
</select>
<div id="phpoutput"></div>
<script>
$('#select').change(function() {
$('#phpoutput').load('?value=' + $(this).val());
});
</script>
<?else:
$val = $_GET['value'];
echo "$val sent to server. $val*3 = " . $val *3;
?>
<?endif;?>

Creating and populating a select dynamically

I have 2 tables, Provinces and Districts. I would like to populate a select field with options as District names based on which Province is chosen in another select. The Districts table has a ProvinceID field to reference which Province it belongs to. I know this is doable, I just can't figure it out. I also want to create and update the new Districts select without refreshing the page.
UPDATE: I'm writing it in PHP and MySQL, using jQuery as sparingly as possible.
In order to do it without AJAX, prepopulate a Javascript dataset... warning, if you have a lot of data this could be slow, but if it's a manageable list length, you could save some overhead from multiple AJAX requests loading the same data over and over.
var provinces = {};
provinces['province_a_id'] = [
{ name:'District A', id:'district_a_id' },
{ name:'District B', id:'district_b_id' }
];
provinces['province_b_id'] = [
{ name:'District C', id:'district_c_id' },
{ name:'District D', id:'district_d_id' }
];
function getDistricts( referenced_select ) {
var selected_province = $(referenced_select).val();
var district_select = $('#districts');
district_select.empty();
if ( provinces[selected_province] ) {
$.each( provinces[selected_province], function(i,v) {
district_select.append( $('<option value="' + v['id'] + '">').text( v['name'] ) );
} );
}
}
$(document).ready( function() {
$('#provinces').bind( 'change', function() {
getDistricts(this);
} );
} );
-- HTML
<select id="provinces" name="provinces">
<option value="province_a_id">Province A</option>
<option value="province_b_id">Province B</option>
</select>
<select id="districts" name="districts">
</select>
Make a php script and call it dp.php ( dp, short for data_provider, use any name you like). In dp.php
// get province id passed in via `post` or `get`
$pid = $_REQUEST['pid'];
// get the districts in that province
$query = "SELECT `district_id`, `district` FROM `districts` WHERE province_id` ='$pid'";
// link to your database
$link = mysqli_connect(HOST, USER, PASS, DBNAME);
// execute your query
$result = mysqli_query($link, $query);
// parse the options
while($row = mysqli_fetch_assoc($result)) {
$options .= '<option value="' . row['district_id'] . '">' . $row['district'] . "</option>\n";
}
// send options
echo $options
With the following markup in your page:
<select id="province" name="province">
<option value="ny">New York</option>
...
</select>
<select id="district" name="district">
</select>
Include the following jQuery:
// whenever a different province is selected
$('#province').change(function() {
// remove all options in district select
$('#district').html('');
// find the new province selected
var my_province = $('#province').val();
// get new options from server and put them in your district select
$('#district').get('path/to/dp.php?pid=' + my_province);
)};
You didn't state what server side technology you are using (if any). Here's an example in ASP.net - it should point you in the right direction:
http://www.mikesdotnetting.com/Article/97/Cascading-DropDownLists-with-jQuery-and-ASP.NET
I actually figured this out on my own using jQuery and post. On the primary select, I added onchange="getDistricts()" and used this for that function:
function getDistricts()
{
var province_id = $("#provinces").val();
$.post("handler.php",
{
"mode" : "get_districts",
"pid" : province_id
},
function(data)
{
$("#districts").html(data);
}, "text");
}
And then in handler.php, I have a case that catches the mode, and runs the following code:
<query on districts table>
while($row = $sql->fetchrow($result);
{
$id = $row['id'];
$name = $row['name'];
$html .= "<option value='$id' id='$id'>$name</option>";
}
echo $html;
I'm not a fan of this solution, and would really like something better, but it does what I need it to do for the moment. I hope this can help someone else out.

Categories