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.
Related
I have a cascading select up and running. I want it that when I click a country only its relevant areas will be displayed.
Now that works until I submit a form. Once the form is submitted, the value from the newly created area list is set to the default that is set before the list is populated.
Before Submitting :
After Submitting :
I want it to work similar to this form of list : Link To Example of choice being the default of a dropdown list If you click link 1 you will see that a location of 'Carlow' is set. When you click on that dropdown its starting point is Carlow. I have attempted two jquery functions. 1. populates the second list with the choice of the first and 2. is an attempt at sending the second choice aswell as the country to try and set it as a default.
I currently have a getoptions.php file :
$sql = "SELECT area FROM Country ORDER BY county ASC";
$result = mysqli_query($conn,$sql);
while($state = mysqli_fetch_assoc($result)){
$area =$state['area'];
//get the location if it is set, if not set let it be null
$location = isset($_GET['location']) ? $_GET['location'] : NULL;
$selectedString = "";
if($location && ($area == $location)){
$selectedString = "selected";
}
echo "<option $selectedString value='$area'>$area</option>";
}
And the main page :
<select name="location" id="location">
<option>Please choose a location</option>
</select>
<script>
$("#country").on('change', function() {
var country = $(this).val();
$("#location").load("/getoptions.php?country="+country);
});
$("#submit").on('click', function() {
var country = $('#country').val();
var location = $('#location').val();
$("#location").load("/getoptions.php?country="+country+"&location="+location);
});
Does this help a bit? It should hand back all areas, and if a location parameter is set it should select that location.
//I'm assuming your table is set up something like this
//id | country | area
//This code checks if there's a country parameter set and if there is
//it uses gets all the areas for that country
$country = (isset($_GET['country']) ? $_GET['country'] : NULL;
$sql = "SELECT area FROM Country ";
if($country){
$sql.= " WHERE Country.country = '$country' "
}
$sql.= "ORDER BY county ASC";
$result = mysqli_query($conn,$sql);
while($state = mysqli_fetch_assoc($result)){
$area = $state['area'];
//get the location if it is set, if not set let it be null
$location = (isset($_GET['location']) ? $_GET['location'] : NULL;
$selectedString = "";
if($location && ($area == $location)){
$selectedString = "selected";
}
echo "<option $selectedString value='$area'>$area</option>";
}
If you go to the above file in the browser with url:
www.site.com/getoptions.php?country=Ireland&location=Dublin
It should output something like the following:
<option value="Antrim">Antrim</option>
<option value="Armagh">Armagh</option>
<option value="Dublin" selected>Dublin</option>
If you get the above out put you're on the right track. If not there's an error with the php.
On your main page try something like this:
<select id="country">
<option value="Ireland">Ireland</option>
</select>
<select id="location">
</select>
<script>
$(document).ready(function(){
$("#country").on('change', function() {
var country = $(this).val();
$("#location").load("/getoptions.php?country="+country);
});
$("#submit").on('click', function() {
var country = $('#country').val();
var location = $('#location ').val();
$("#location").load("/getoptions.php?country="+country+"&location="+location);
});
}); //doc ready
See if that puts you on the right track.
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>');
}
});});
I have a couple of SELECT boxes that are pulling from the database, how can I get the option that is selected in SELECT box 1 to filter the SQL in the SELECT box 2?
EG SELECT 1 - Make (Audi, BMW) SELECT 2 - Model (A1,A3, 1 Series, 3 Series)
I want to show that if I pick Audi from SELECT 1 that it will use Audi to fill the WHERE clause in my SQL to filter for the SELECT 2
<label>Manufacturer</label>
<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1" id="make" name="make" >
<option value=""></option>
<?php $sqlmake = odbc_exec($cnn, "SELECT DISTINCT Manufacturer FROM lkup.alldata ORDER BY Manufacturer ");
while($manurs = odbc_fetch_array($sqlmake)) {
echo '<option value="'. $manurs['Manufacturer'] .'">'. $manurs['Manufacturer'] .'</option>';
}
?>
</select>
From the above I've been working on this below, which returns no errors but also when you click on the SELECT returns no values in the SELECT.
Where have I gone astray?
My SELECT
<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1" id="model" name="model">
<option value=""></option>
</select>
<script>
$(function() {
$('.make').change(function() {
var select = $('.model').empty();
$.get('assets/configs/script.php', {model: $(this).val()}, function(result) {
$.each(result, function(i, item) {
$('<option value="' + item.value + '">' + item.name + '</option>').
appendTo(select);
});
});
});
});
</script>
The script.php
<?php
session_start();
date_default_timezone_set("Europe/London");
error_reporting(0);
include 'config.php'; //my db settings
if (isset($_GET['model'])) {
$model = addslashes($_GET['model']);
$sqlmodel = odbc_exec($cnn, "SELECT DISTINCT ModelName FROM lkup.MyTable WHERE ModelName IS NOT NULL AND Make = $model ORDER BY ModelName ");
$modelrs = array();
while ($row = $sqlmodel->fetch_assoc()) {
$modelrs[] = array(
'ModelName' => $modelrs['ModelName']
);
}
echo json_encode($modelrs);
}?>
If you are familiar with javascript or jQuery you could run another php echo statement to create the other select options with all the possibilities, and then with jQuery hide or show the appropriate options.
$('select[name=first_select]').on('change', function(){
var make = $(this).val();
$.each($('select[name=second_select] option'), function(){
if($(this).prop('class') != make){
$(this).hide();
}
}
});
After a lot of problems with this I found this link that worked a treat. I think my main problem is that I'm using PHP & MS SQL Server, which makes life difficult.
This I found as my solution
hope you can help as I'm starting to pull my hair out :) There seems to be loads of links around regarding this but I can't get any of them to work, so I'm just going to ask in straight laymans terms.
I have a database... it has fields for Region, Area, Manager, Employee
I have a front end form, with select boxes in it...
When you choose the Region, I need the Area selectbox to dynamically populate with the relevant areas from the database without refreshing the page
Then when the Area selct option is chosen the Manager one needs to populate. and so on.
No doubt this needs an ajax/ Jquery solution, of which as I've said there's many articles around about this but I just cannot get them to work. I've NEVER even attempt AJAX before today so sincere apologies if this is a total noob thing to be asking.
Any help or guidance would be greatly appreciated. Thankyou!
Okay I have this for my Jquery:
$(document).ready(function() {
$('#Region').change(function() {
// remove all options in Area select
$('#Area').html('');
// find the new Region selected
var selected_region = $('#Region').val();
// get new options from server and put them in your Area select
$('#Area').get('Ajax/getArea.php?Region=' + selected_region);
});
});
and this for my PHP:
<?php
// get province id passed in via `post` or `get`
$region = $_REQUEST['Region'];
// get the districts in that province
$query = "SELECT DISTINCT AREA FROM Sales_Execs WHERE Region ='$region'";
// link to your database
$link = mysqli_connect("localhost", "root", "", "Quality_Monitoring");
// execute your query
$result = mysqli_query($link, $query);
// parse the options
while($row = mysqli_fetch_assoc($result)) {
$options = "<option value=\"".$row['AREA']."\">".$row['AREA']."</option>\n ";
}
// send options
echo $options;
?>
And still no joy... can anyone spot what I'm missing?
try this, there are 3 different sections I have included in the code:
1) the PHP code
2) The jQuery
3) The select box container
:: Your PHP file (call it getArea.php)
$selectbox = '<select name="region" onchange="jQuery.selectRegion(this.value)">';
$region = $_REQUEST['Region']; /* Make sure you escape this */
$query = "SELECT DISTINCT AREA FROM Sales_Execs WHERE Region ='$region'";
$link = mysqli_connect("localhost", "root", "", "Quality_Monitoring");
$result = mysqli_query($link, $query);
$options = '';
while($row = mysqli_fetch_assoc($result)) {
$options .= '<option value="' . $row['AREA'] . '">' . $row['AREA'] . '</option>';
}
echo $selectbox;
echo $options;
echo '</select>';
exit;
:: Your jquery
jQuery.selectRegion = function selectRegion(regionId)
{
$.get('ajax/getArea.php?region='+regionId,function(data){
$('#select_container').html(data);
});
}
:: The select box container
<div id="select_container">
<select name="region" onchange="jQuery.selectRegion(this.value)">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
Hope this helps
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/