I want to make a DropDown Menu, where someone can Choose an option out of several options. Ans depending on this Value the other Dropdown menu should be updated with values out a Database.
Like
Option 1: kind of sport
Option 2: Time
Option 3: Place
.
.
.
// EDIT adding actual option.
$query = 'SELECT * FROM kurs';
$result = $mysqli->query($query);
echo
"<table border = 1>
<tr align = 'middle'>
<td> <select>";
while ($zeile = $result->fetch_assoc()) {
echo "<option>" . $zeile['name'] . "</option>";
}
$result = $mysqli->query($query);
echo
"</td><td> <select>";
while ($zeile = $result->fetch_assoc()) {
echo "<option>" . $zeile['day'] . "</option>";
}
$result = $mysqli->query($query);
and if someone update choose one option out of 'day', the other option 'name' should change depending on the 'day' and vice versa.
I know how to get the information out of my SQL Database but i don't know how to make the Select Area dynamic. I'm not allowed to use JQuery.
Any help is appreciated
Summary: Use a <select onchange... event, XMLHttpRequest, and two PHP scripts.
To simplify the discussion, let's forget about Sport. The user first chooses a race date and then chooses an entrant name. Initially, the date dropdown shows all the dates, and the name dropdown is blank. After selecting a date, the name dropdown is populated with all the names for that date.
And suppose the database is so large that you don't want to send all the data to the browser in one go. You only want to send the names after the user has chosen a date.
This is classic AJAX. If you don't use jQuery (or another Javascript library), then you need to roll-your-own by using XMLHttpRequest (see http://www.w3schools.com/ajax ). That's what jQuery does.
Now, to examine your code. 'SELECT * FROM kurs' is going to give you all the records in the database. If you have 1000 records, your Date dropdown will have 1000 options! You might want:
SELECT DISTINCT [day] FROM kurs ORDER BY [day]
If you want the Date dropdown to feed names into the Name dropdown as soon as the user chooses a date, without the need to click a Submit button, then do this:
$optionlist = '<option value="">--Choose Race Date--</option>';
while ($zeile = $result->fetch_assoc()) {
$optionlist .= '<option>' . $zeile['day'] . '</option>';
}
echo "
<table border='1'><tr>
<td><select onchange='datechange(this)'>$optionlist</select></td>
<td id='tdSelectName'><select disabled></select></td>
</tr></table>";
The --Choose Race Date-- option is there so that if the user happens to want the first date then there will still be an onchange() event.
Your Javascript will need:
function datechange(sel) {
raceDate = sel.value;
if ( raceDate ) {
var myRequest = ...
// your synchronous XMLHttpRequest code goes here
document.getElementById("tdSelectName") = myRequest.responseText;
}
}
To see a fancier version of this in action, look at http://www.mostbryte.com/where_to_buy
Related
Im trying to modify a calculator PHP which is based on drop down selections
I have 5 Drop downs. One of which when the value is selected it outputs either "18" or "72" based on what is selected. Within that table is another column which has the values "1" "0.5" "0.4" "0" how do I get the drop down to select both rows to help me get them into a string for calculation?
This is the input / selector (this is where i need to add the extra row based on what the user selects in the drop down)
<?php
while ($row = mysqli_fetch_array($bunkernic)) {
echo '<option value="'.$row['nic_mg'].'"'.($_POST['nic'] == $row['nic_mg'] ? " selected": "").'>'.$row['select_nic'].'</option>';
}
?>
Currently that outputs the nic_mg to a $input which changes when a user selects (i can see this when i use print_r ($input);)
Could anyone guide me to achieve this?
If you need any more info / or files to take a look at let me know
I may not be making any sense here, I'm a complete beginner at this but I feel I'm picking little bits up
Thanks
Put both column values into the value attribute, with a delimiter between them.
$val = $row['nic_mg'].'|'.$row['other_column'];
echo '<option value="'.$val.'"'.($_POST['nic'] == $val ? " selected": "").'>'.$row['select_nic'].'</option>';
Then when the form is submitted, you can split the value:
list($nic_mg, $other) = explode('|', $_POST['nic']);
First SELECT:
<?php
function select_size($itemSizes){
echo "<select id=\"size\" name=\"size\">";
$sizes = array("0" => "All Sizes","1" => "Large","2" => "Medium","3" => "Small");
foreach($sizes as $s => $si){
if($itemSizes == $s){$selected = "selected";}
echo "<option value=\"" . $s . "\" $selected>" . $si . "</option>\n";
$selected = "";
}
echo "</select>\n";
}
?>
Second SELECT:
$(document).ready(function() {
$("#eventCategory").change(function() {
var val = $(this).val();
$("#eventType").html(options[val]);
});
var options = ["
<option value='all_items'>ALL Items</option>
<option value='red'>red</option>
<option value='blue'>blue</option>
<option value='green'>green</option>
];
});
First select retains value due to PHP. onChange is working properly as once a value in Select #1 is chosen, Select #2 populates with it's appropriate list. The problem I'm having is Select #2 is not retaining it's value through a POST and page reload. I've worked out a bit of JS that does this but it fouls up the onChange function. I'm trying to achieve both at the same time and have failed thus far. Yes, I'm an amateur with JS. Pretty good with many other languages. The syntax is causing me troubles. Any assistance is greatly appreciated.
You can send an ajax when first select triggers onChange event.
Then, on the success of this Ajax, you can get values from php and changing the second one. As you are using ajax, the first option will not be modified.
As you asked for "reloading page" you will need to print a script in the view that browsers can render, this can look like:
if you can know the ID of each option (if any):
echo "<script> $('#selector1 option#'.$idOption.').attr('selected', 'selected'); </script>";
if you can't know the ID of each or there are any id to catch, you'll get the value for sure, the script will look like:
$('#selector1 option[value="'.$value.'"]').attr("selected", "selected");
where in the first case $idOption is the id of the option selected on first selector and retrieved from php. $value in the second script is.. well, the value.
don't really know if there solves your entire problem as i can only see a part of your code, i'll edit it if you provide feedback.
Maybe you would var_dump / console.log values for getting a backtrace of your data and see where it's lost to ensure you pass the needed data around your functionallity.
Please someone help, I am really stuck on this for 2 days :|
I have a PHP form and I would like to enable user select movies by title, or by actors.
So, I was thinking about a dropdown menu by these values (moviebyTitle, moviebyActor). For selecting movies by title, I used jQuery auto-complete which get movie titles from my DB and it works fine.
This is my code:
<select id="selectType" name="source">
<option value="">MoviesBy</option>
<option value="byTitle">byTitle</option>
<option value="byActor">byActor</option>
</select>
<input type="textbox" name= "tag" id="tags">
<div id="byActor" class="style-sub-1" style="display: none;" name="stylesub1" onchange="ChangeDropdowns(this.value)">
<select name="films[]" multiple="multiple" width="200px" size="10px">
<?php
include('moviedropdown.php');
?>
</select>
and here is the javascript:
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2
});
$("#selectType").change(function () {
if ($(this).val() == "byTitle")
$("#tags").autocomplete("option", "source", "filmsauto.php");
else
if ($(this).val() == "byActor")
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal, q2: $("#selectType").val()}, function (response){
// response variable above will contain the option tags. Simply put in the dropdown.
$("#movieImdbId").html(response);
});
}
});
}
});
});
</script>
EDIT:
and this is the actions.php: (please kindly see also javascript part above)
<?php
if(isset($_GET['q']) && !empty($_GET['q']) && isset($_GET['q2']) && !empty($_GET['q2']) ){
// Here goes the cleaning code. Never use the variables received from $_GET and $_POST directly before processing it for malicious code.
$q = $_GET['q'];
$q2 = $_GET['q2'];
//$sql = fetchResults($q, $q2); // Some function which will run a database query and return some records in either object collection or arrays etc.
//I added this part to fetch data from DB
include('imdbConnection.php');
$sql = $conn->prepare('SELECT DISTINCT movieImdbId FROM movie_roleNames WHERE castName = :q');
$sql->execute(array(':q' => $q));
$html = "";
while($row = $sql->fetchAll(PDO::FETCH_OBJ)){
$option = '<option value="' . $row->movieImdbId . '">' . $row->movieImdbId . '</option>';
$html = $option;
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
?>
My question:
I just wonder how can I add a drop down list based on the value user has typed in the textbox. For example, if user wrote "Tom Cruise" in the auto-complete textbox, a dropdown will be added that shows movies in which "Tom Cruise" has played. (I make a COMMENT in the JavaScript code where I had problem)
I really searched a lot, but all samples where to dynamically populate some dropdown (like this one, or adding a textbox based on value selected in dropdown...
Please help, I really don't mean someone write the code for me, I just want to find any sample or some way that I can learn how to do it.
Thanks,
You should have something like the following.
What you actually need is when you type into the auto complete box and select something, you need to get a hold of that value for later use. After that, you need to call the server (a php script) with an ajax call and send that value from the autocomplete box along with the value from the drop down (only if you need to). That php script will need to generate a pile of something like the following in loop and save the whole html in a variable.
<option value='v1'>Value1</option>
<option value='v2'>Value2</option>
After that, send that back to the calling ajax script and then you need to put this as the content inside that drop down that you're trying to populate.
Here's some sample code on how to accomplish the javascript part.
<select id="filmsdd" name="films[]" multiple="multiple" width="200px" size="10px">
</select>
<script>
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal, q2: $("#selectType").val()}, function (response){
// response variable above will contain the option tags. Simply put in the dropdown.
$("#filmsdd").html(response);
});
}
});
});
<script>
EDIT:
path/to/somefile.php would be any file which is stored in your directory along with other website files. let's call it actions.php (I have updated the $.post ajax call)
When $.post runs, it will send a request to actions.php along with two variables q and q2. These variable names can be anything.
q contains the selected value from the auto complete box.
q2 contains the selected type from the drop down.
in actions.php, you end up with something like this.
if(isset($_GET['q']) && !empty($_GET['q']) && isset($_GET['q2']) && !empty($_GET['q2']) ){
// Here goes the cleaning code. Never use the variables received from $_GET and $_POST directly before processing it for malicious code.
$q = $_GET['q'];
$q2 = $_GET['q2'];
$sql = fetchResuls($q, $q2); // Some function which will run a database query and return some records in either object collection or arrays etc.
// Initialize a variable that you will send back to your ajax call, its still waiting for this script to be completed.
$html = "";
// Assuming your function returned a list of objects. Loop through the records.
while($row = mysql_fetch_object($sql)){
$option = '<option value="' . $row->property_id . '">' . $row->property_name . '</option>';
$html .= $option;
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
I hope this helps.
The real question is, what's the point of the second drop down box. Why dont you just display all of the movies in a "table" once they've selected the actor.
I'd suggest a unified "Search" box, and on the PHP side, querying both your movies and actors, displaying all results that way?
If they choose a autoComplete value that is of type actor, display all the actor's movies. If they select an autoComplete value that is of type "movie" - display all the movies.
Effectivly - you're eliminating the By Actor or By Movie radio in favor of a better search bar.
I am trying to get this to allow the user to click on a link, which will then change the value of what is submitted in the SQL SELECT Statement, if that makes sense.
My Code so far:
<div class="Tabs" >
<?php
require 'database/connect.php';
$sql = "SELECT DISTINCT Week FROM PMWUpdates";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo '<a class="weeks"> Week' . $row{'Week'} . '</a>';
}
?>
</div>
<div class="Pages">
<?php
require 'database/connect.php';
$sql = "SELECT * FROM PMWUpdates WHERE Week='1'";
?>
</div>
I want the value of SELECT * FROM PMWUpdates WHERE Week="'1'"; to be what link the user has clicked on above, not just always 1. So if the user clicks on the link 2, the SQL changes to SELECT * FROM PMWUpdates WHERE Week="'2'";
I am basically trying to accomplish this, but instead, I want to display the number of tabs, based on the number of weeks in a database, and then, each week will display data from the database about that particular week.
Any help is appreciated.
Thank You
Your statement should be like this...
$sql = "SELECT DISTINCT Week FROM PMWUpdates";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo '<a class="weeks" href="$row['Week_link']"> Week' . $row['Week'] . '</a>';
}
If you mean dynamically changing data on a page which requires PHP to be processed, you have to take a look at AJAX. You can't do it this way, once your script is loaded, there is no more php, only HTML.
If you don't want to use AJAX, you will have to do it in 2 pages. First display links, then display your data related to whatever was selected.
The MySQL extension you are using is deprecated (>= 5.5). Use MySQLi or PDO instead.
What you are trying to accomplish is that where your "2" is listed, should change with the use of a variable. As you want to do it via Javascript, you will need a click event on those links which then submits the variable via AJAX.
i have totally no idea about how to do this, so i'm gonna just ask away.
I have a dropdown menu which list dates say
1/2/2013
2/2/2013
3/2/2013
4/2/2013
5/2/2013
6/2/2013
7/2/2013
if you were to select one of the dates, a div will pop out with say 5 choices
A
B
C
D
E
each choices are stored in the database, and if say B item is not available on 2/2/2013, i would have a script to disable it being selected. I've figured how to create that in php, but my ultimate question is
how do you select any of the dates but yet still able to retrieve the 5 choices from a database?
I'm currently doing something like this
function TheDisabler($aa)
{
global $con, $vdate;
$myresult = mysqli_query($con,"SELECT * FROM burger WHERE timeslot = '$aa' AND date = '$vdate'");
list($mycount) = mysqli_fetch_row($myresult);
if($mycount >= 1) {
echo "disabled";
}
}
but i figured that this works only once and if i were to change the date, the items within the div will not change =/
You should have a script that works every time the div element is clicked. So add an onClick event to div and then retrieve the required data from database on that event's handler.
if your table does not have large amount of data, create a php file that behave as if it's a javascript file like that:
<?php
$js = 'data = new Array()';
$sql = 'select ...';
$count = 0;
while($row = fetch_rows($sql)){
// do your check here
$js .= 'data[' . $row['date'] . '] = new Array()';
$js .= 'data[][' . $row['date'] . '][$count] . ' = "'.$row['item'] . '";';
$count++;
}
header('Content-Type: text/javascript');
echo $js;
?>
now you have a javascript array which have every date items, then on each click ask this array for that date key should return you the your options list
I think what you are looking for is the onchange event of the ckeck box. Each time there is a change in the drop down, call the function to retrieve the values from the database.