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
Related
I am trying to accomplish two things with the code below. Firstly I want my select options to be populated form my database. Secondly I want the field in the form to have the stored value selected on page load (like in a profile for a member). The way I have implemented below works, kind of, but I have two problems. Firstly if you open the dropdown then the selected option appears twice (once at the top and once in its normal position). Secondly if it is a required field then the user has to open the dropdown and select it again, even though it is appearing in the field (horrible ux). If it is not a required field the form acts as if nothing is selected and I get a Undefined index error further down the line. I am very sure there is a better way to implement what I am trying to achieve that wont give me these problems... all help greatly appriciated.
<?php
$query6 = "SELECT catname FROM travisor_catagory";
$result6 = mysqli_query($conn, $query6) or die(mysqli_error($conn));
$queryread3 = "SELECT * FROM travisor_catagory WHERE id = $catagory";
$result3 = mysqli_query($conn, $queryread3) or die(mysqli_error($conn));
if (mysqli_num_rows($result3) > 0) {
while ($row = mysqli_fetch_assoc($result3)) {
$cat = $row["catname"];
}
}
echo "<div class='form-group'>
<label>Catagory *</label>
<select class='form-control' name='catagory' required>
<option disabled selected value> $cat </option>";
if (mysqli_num_rows($result6) > 0) {
while ($row2 = mysqli_fetch_assoc($result6)) {
$catagory2 = $row2["catname"];
echo "<option>$catagory2</option>";
}
}
echo "</select>"
?>
Don't mix things up so much.....
When you get into larger programs, you will get lost really quickly, so K.I.S.S.!!!
You can 'jump' in/out of HTML and back to PHP to echo the $options variable, then back to HTML to complete the select. (this is my description of it when I teach newbies - this concept of 'jump in/out' works for PHP, HTML, JS - well any languages that you can combine in one page... - it is worth grasping the concept!)
First, get the options you will need with ONE query (watch how we take care of the selected one as well) - this will make a 'packet' of data in the $options variable.
<?php
// declare some values that we'll use later
$options = '';
// gather the data for the options
$sql = "SELECT id, catname FROM travisor_catagory";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$selected = '';
if($category == $row['id']){
$selected = "selected";
}
$options .= '<option ' . $selected . ' value="' . $row["id"] . '">" . $row["catname"] . "</option>";
}
}
// now we will 'jump' out of PHP and back to HTML
?>
<!-- we are in HTML, so comments and language changed... -->
<div class='form-group'>
<label>Catagory *</label>
<select class='form-control' name='catagory' required>
<!-- here we 'jump' out of HTML and into PHP to use the $options variable -->
<?php echo $options; // and back out of PHP to HTML... ?>
<!-- where we finish up our select and whatever other HTML things -->
</select>
</div>
That should take care of both your issues with what you had.....
BTW, it looks like you are using Bootstrap - if so, I HIGHLY recommend you check this out (changed my life about fighting with select boxes! :) Bootstrap Select
Okay, I'm reframing this whole question because the earlier version was a bit convoluted.
Here's the scenario:
I have a MySQL table called "churches."
I have a form with four selects. The options are drawn dynamically from the table, so that users can search on four table columns to find churches that fit the criteria (country, state/province, city, presbytery)
I also have working code to get all the table data to display.
What I haven't figured out is how to use the selected option from the form to filter the results.
My current code is below:
<form action="display0506b.php" method="post">
<select name="country">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT country FROM churches");
$query_display = mysqli_query($link,"SELECT * FROM churches");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['country'] . "</option>";
}
?>
</select>
<select name="state">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT state FROM churches WHERE state != ''");
$query_display = mysqli_query($link,"SELECT * FROM churches WHERE state != ''");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['state'] . "</option>";
}
?>
</select>
<input type="submit" value="Go!">
</form>
<?php
if(isset($_POST['country']))
{
$name = $_POST['country'];
$fetch = "SELECT * FROM churches WHERE id = '".$name."'";
$result = mysqli_query($link,$fetch);
echo '<div class="churchdisplay">
<h4>' .$row['churchname'].'</h4>
<p class="detail">' .$row['detail'].'</p>
<p><b>' .$row['city'].'</b>, ' .$row['state'].' ' .$row['country'].'</p>
<p>' .$row['phone'].'</p>
// etc etc
</div>';
}
else{
echo "<p>Please enter a search query</p>";
}
?>
Note that in the form above, I only have two selects for illustration, but ultimately I will have four, as mentioned; and I am only attempting the country selection at this point to keep things simple. Ultimately, I will need the ability to select any (and preferably all) of the four categories.
As you can see, this code does attempt to "grab" the selected value from the form, but it's not working. I've pondered numerous tutorials and examples, but none of them do exactly what I'm after, and as an extreme PHP novice, I'm stumped.
So the question: how do I tweak this so that I can "grab" the form selection and display the relevant results from my table?
Edit: I am using mysqli syntax, and want to just use PHP and MYSQL (no Ajax etc) if possible.
Well, it looks like I've finally found what I needed here:
display result from dropdown menu only when value from it is selected
Or, I should say, I've got it to work with one select option. Still need to see if I can figure out how to get four working together.
I have searched quite a bit on here about this topic. But I could not find a solution for my problem. I'd appreciate it a lot if you could help me, this is for a school project I am working on.
I have a database with a table ("Main_table") and columns including "sector" and "sub_sector". I want to have two select boxes, first one will load all the records from database in "sector" column and the second one will load all the records from database in "sub_sector" column depending on the selection value of the first select box. (For example: If I select "plastics" on the first select box, then second select box should be updated with sub_sector values where sector value is equal to "plastics").
I have managed to load the options values from database for the first select box but when I click on any selection, it does not load any option to the second select box. You can find the codes below. I did not put "sector_options.php" below, as it seems to work just fine.
index.html shown below:
<script>
$(document).ready(function() {
$('#filter_sector')
.load('/php/sector_options.php'); //This part works fine - uploads options to the first select box
$('#filter_sector').change(function() {
$('#filter_subsector').load('/php/subsector_options.php?filter_sector=' + $("#filter_sector").val()
} //This part does not work - no options on the second select box
);
});
</script>
<body>
<div id="sectors"><p>Sector:</p>
<select id="filter_sector" name="select_sector" multiple="multiple" size="5"> </select>
</div>
<div id="subsectors"><p>Sub Sector:</p>
<select id="filter_subsector" name="select_subsector" multiple="multiple" size="5"> <option value="" data-filter-type="" selected="selected">
-- Make a choice --</option>
</select>
</div>
</body>
</html>
sector_options.php shown below:
<?php
$link = mysqli_connect("*******", "*******","******","********") or die (mysql_error());
$query = "SELECT sector FROM Main_table ";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {
$options .= "<option value=\"".$row['sector']."\">".$row['sector']."</option>\n ";
}
echo $options;
?>
subsector_options.php shown below:
<?php
$link = mysqli_connect("********", "*****,"*******", "********") or die (mysql_error());
$Sectors = $_REQUEST['filter_sector'];
$query = "SELECT sub_sector FROM Main_table WHERE sector='$Sectors'";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {$options .= "<option value=\"".$row['sub_sector']."\">".$row['sub_sector']."</option>\n ";
}
echo $options;
?>
For completeness, the solutions were:
Check how AJAX operations are doing using a browser network monitor
Load AJAX fetcher scripts in a browser tag - in many cases they will render quite happily there, allowing them to be more easily debugged
AJAX scripts that return HTML for injection should only return that HTML, and not a full HTML document.
I have 2 dropdown select boxes in my form. The first one allows the user to choose a car make "vmake". Once a vmake is chosen a "vmodel" select box appears from thin air and then the user can choose the vmodel. However, I want the vmodel box to be there on page load, so it doesnt just appear out of thin air. It would be empty if the user tries to open it until they select a vmake. Heres my html
<select name="vmake" id="vmake">
<option value"" selected="selected">Make</option>
<?php getTierOne()l ?>
</select>
<select name="vmodel" id="vmodel">
<option value"" selected="selected">Model</option>
</select>
<span id="wait_1"></span>
<span id="result_1"></span>
Heres the jquery:
$(document).ready(function(){
$('#wait_1').show();
$('#vmake').change(function(){
$('#wait_1').show();
$('#result_1').hide();
$.get("func.php", {
func" "vmake",
drop_varL $('#vmake').val()
}, function(response){
$('#result_1').fadeOut();
setTimeout(finishAjax('result_1', '"+escape(response)+"')", 400);
});
return false;
]);
});
lastly the php which connects to my database
function getTierOne()
{
$result = mysql_query("SELECT DISTINT vmake FROM vmake")
or die(mysql_error());
while($tier = mysql_fetch_array( $result ))
{ echo '<option value="'.tier['vmake'].'">'.$tier['vmake'].'</option>';
}}
if($_GET['func'] == "vmake" && isset ($_GET['func'])) {
vmake($_GET['drop_var']);}
function vmake($drop_var)
{ include_once('db.php');
$result = mysql_query("SELECT * FROM vmake WHERE vmake='$drop_var'")
or die(mysql_error());
echo '<option value=" " selected="selected">Model</option>';
while($drop_2 = mysql_fetch_array( $result))
{ echo '<option value="'.$drop_2['vmodel'].'">'.$drop_2['vmodel'].'</option>';
}}
I got some help with the original code form an open source website and now I just need to change it a little to make it do what I want. As it stands it will create a new vmodel select box next to the existing one, but I just want it to populate the select box that appears on page load. Any help is very much appreciated. Thanks for everything.
Did you try using jQuery .load?
Example:
$('#vmodel').load('func.php',{vmake:$('#vmake').val()});
Would need to change the PHP as well, so you make a normal array of values and then send it through json_encode().
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.