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.
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'm writing a jQuery mobile page (with PHP) that populates a select element and it's option tags with "items" from a table in a MySQL database (the table contains id, items, cost). Using the commonly cited mysql_query and while mysql_fetch_assoc method to echo out the options this works fine. Stripping to the bare code:
<?php
$itemQuery = mysql_query("SELECT shortDesc FROM `items` ORDER BY shortDesc");
?>
<label for="item" class="select">Item:</label>
<select name="item" id="item" data-native-menu="false">
<option>Select Item:</option>
<?php
while($temp = mysql_fetch_assoc($itemQuery))
{
echo "<option value='".$temp['shortDesc']."'>".$temp['shortDesc']."</option>";
}
?>
</select>
I'd like however to be able to update the input element below that called "cost" with the actual item's cost from the MySQL table, when the user selects an item from the list, and I'm uncertain how to do that using jQuery/PHP/MySQL. The cost input field:
<label for="cost">Cost:</label>
<input type="text" name="cost" id="cost" value="" placeholder="Cost (£)"/>
I'm also not sure if we can get the cost value somehow from the results already returned in $itemQuery (by changing the SELECT to shortDesc,cost) saving another database query, or whether we do have to query the database again to perform a select where the user's selection = shortDesc.
I suspect in different forms, this is a common requirement for developers; essentially grabbing some information from a database based on a user's selection / interaction. I have looked on Google and searched here but I am not sure if I'm using the right search terms to find what I suspect will already be answered elsewhere!
Help greatly appreciated as always.
You could do:
1) Loop through your query results and write your options and some javascript (i use an Associative Array)
<?php
$result = mysql_query("SELECT shortDesc,costs FROM items ORDER BY shortDesc");
$options = '';
$javascript = '';
while ($row = mysql_fetch_assoc($result))
{
$options .= '<option value="'.$row['shortDesc'].'">'.$row['shortDesc'].'</option>';
$javascript .= '\''.$row['shortDesc'].'\' : \''.$row['costs'].'\',';
}
?>
2) write your html and javascript:
<select id="yourselect">
<option>select</option>
<?=$options?>
</select>
<label for="cost">Cost:</label>
<input type="text" name="cost" id="cost" value="" placeholder="Cost (£)"/>
3) write some javascript to update your input field:
<script>
var costs = {<?=$javascript?>};
$(function() {
$('#yourselect').change(function() {
cost = costs[$('#yourselect').val()];
$('#cost').val(cost);
});
});
</script>
I wish to use dropdown to list all rows from database. When I select one option, delete that selected row with button.
Here what I have by now, this only shows dropdown:
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Nije se moguće konektovati: ' . mysql_error());
}
mysql_select_db("videoteka", $con);
$result = mysql_query("select ime,id from filmovi");
$options="";
echo "Odaberite film:";
while ($row=mysql_fetch_array($result)) {
$id=$row["id"];
$ime=$row["ime"];
$options.="<OPTION VALUE=\"$id\">".$ime.'</option>';
}
mysql_close($con);
And in body:
<select name=thing>
<option value=0><?=$options?></option>
</select>
Ok, so two things, just to try and put you in the right direction: first, in the body you can remove the <option> tag, since your php variable already contains those.
<select name=thing>
<?=$options?>
</select>
Second, the delete part. There are different ways to do this, but one thing you will certainly need is an HTML form. Your select (and the button) will need to be in this form, which will be submitted to this very same PHP page. In the beginning of your PHP code you will check the $_POST variable to determine what row to delete. I hope you know what $_POST is, otherwise this is going to be a pretty useless explanation.
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().