I'm trying to make a grade distributions website, and I'm creating 4 dropdowns correlating subject (cs, math, etc.), class (data structures, AI, etc.), professor, and quarter the class was taken. After the quarter dropdown is selected, I want to display a bar graph with the data.
The problem I'm running into is that I can't populate the second dropdown with data Basically, I can successfully pull data from the database for the first dropdown, and if the user selects something then the second dropdown (that was originally hidden using jquery) becomes visible, but it isn't properly pulling data from the database and adding it as options to the second dropdown. An example would be that I can select Computer Science from the first dropdown, then the second dropdown is visible, but it doesn't contain 'intro to programming', 'data structures', etc. in it; instead, it's just blank.
FYI, I'm using these selectpickers: http://silviomoreto.github.io/bootstrap-select/
PHP (error is most likely somewhere in the getClasses function, quite possibly the $_POST section of the code):
<?php
function getSubjects()
{
/* Get mysql connect information from external file and connect*/
require_once 'database.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if($connection->connect_error) die ($connection->connect_error);
/* Get the column containing the subjects from the table */
$query = 'SELECT DISTINCT Subject FROM gradelist ORDER BY Subject';
$result = $connection->query($query);
if(!$result) die ($connection_error);
/* Keep track of the number of rows in the column; necessary for iterating */
$rows = $result->num_rows;
/* selectBar keeps track of the html code for the select Bar*/
$selectBar = '';
for($j = 0; $j < $rows; $j++)
{
$result->data_seek($j);
$value = $result->fetch_assoc()['Subject'];
$selectBar .= '<option>' . $value .'</option>';
}
$result->close();
$connection->close();
return $selectBar;
}
function getClasses()
{
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if($connection->connect_error) die ($connection->connect_error);
if(isset($_POST['subject']))
{
$query = "SELECT DISTINCT Class FROM gradelist WHERE Subject = $subject";
$result = $connection->query($query);
if(!$result) die ($connection_error);
}
else
{
die($connection_error);
}
$rows = $result->num_rows;
for($j = 0; $j < $rows; $j++)
{
$result->data_seek($j);
$value = $result->fetch_assoc()['Class'];
$selectBar .= '<option value = "' . $value . '">' . $value .'</option>';
}
$result->close();
$connection->close();
return $selectBar;
} ?>
HTML Portion of the code (again, the error might be with the $_POST part of the code) :
<form class="form-horizontal" method = "post" role="form">
<div class="form-group">
<div class="col-lg-10">
<select name = "subject" id="subject" class="selectpicker show-tick form-control" data-live-search="true" title ="Subject">
<?php echo getSubjects(); ?>
</select>
</div>
</div>
</form>
<form class="form-horizontal" method = "get" role="form">
<div class="form-group">
<div class="col-lg-10">
<select name = "class" id="class" class="selectpicker show-tick form-control" data-live-search="true" title ="Class">
<?php if(isset($_POST['subject'])) echo getClasses(); ?>
</select>
</div>
</div>
</form>
jQuery:
$(document).ready(function() {
$('#class').selectpicker('hide');
$('#professor').selectpicker('hide');
$('#quarter').selectpicker('hide');
});
$('#subject').on('change', function(){
$('#class').selectpicker('refresh');
$('#class').selectpicker('show');
});
$('#class').on('change', function(){
$('#professor').selectpicker('show');
});
$('#professor').on('change', function(){
$('#quarter').selectpicker('show');
});
$('#quarter').on('change', function(){
showTable();
temp = $('#class').selectpicker('val') + " with " + $('#professor').selectpicker('val') + " during " + $('#quarter').selectpicker('val');
$('#displayName').text(temp);
});
Your PHP is executed with $_POST["subject"] not set, and you never POST the subject the user chose to the page; if you don't make an additional POST request, there's no way for the classes to populate.
One way to do it (without changing any of your files) is like so:
$('#subject').on('change', function(){
$.post({
data: { subject: $(this).val() },
success: function (data) {
var classes = $(data).find("#class");
$("#class").replaceWith(classes);
}
});
});
So when a change event is triggered on the subject selection, we'll POST the selected subject to the current page. The response should be the entire document generated with the class selection filled (since $_POST["subject"] is set).
We then replace the current page's #class select element with the version in the generated data (wrapped in $() to create DOM elements from the stringified HTML, so we can use find()).
Another way might be to have files, getSubjects.php, getClasses.php, and so on, and POST individually to them (you make the first request onload, and subsequent requests onchange). This way, you can just append the generated option elements to the select elements on the page.
ALSO: Please please please sanitize $_POST["subject"] before using it in a database query. A user could easily add a fake option to the select locally with a malicious string for value, and you'd unknowingly query the DB with that. You can use prepared statements for this (mysqli has the prepare() function to prepare a statement before querying). More on that and combating SQL injection here.
Related
I need to get the value of the selected item on the drop down selection populated from sql database. Then that value is needed in the sql statement to get the specific record.
I already populated the drop down selection. Code below
<select name="year" id="year">
<?php
$query = mysql_query("SELECT distinct Year(fromdate) FROM emp WHERE empcode='$emp' order by Year(fromdate) desc");
while ($row = mysql_fetch_array($query)){
$year = $row[0];
echo "<option value=\"".$year."\">".$year."</option>";
}
?>
</select>
This is the php code for me to get the record using the value from the drop down.
<?php
$sql = mysql_query("SELECT salary FROM emp WHERE empcode='$emp' and Year(fromdate) = '$year'");
$row = mysql_fetch_array($sql);
$salary=$row[0];
?>
Then after that I need to pass the result to a textbox
<input id="salary" name="salary" value="<?php echo $salary; ?>">
What is the code needed for me to pass the selected item value from drop down "year" to PHP variable $year for sql statement? I already looked here in Stack Overflow for the answers but there is no question that look like mine.
What is wrong with people it needs sql why vote down
Do an ajax call to your php file, listening to your select onchange event, like so:
$('#year').on('change', function() {
$.post( "path/file.php", {
year: $(this).val()
})
.done(function( data, status ) {
console.log('data: '+data+' status: '+status);
if(status == 'success'){
//pass to your input ?
//data is what your php file will echo/output
$('#salary').val(data);
}else{
//how do you want to handle http error ?
}
});
});
If you want to get select box value without refreshing page then you need to do code with AJAX.
http://api.jquery.com/jquery.ajax/
On change please pass the year value to AJAX and then in AJAX file write down query for salary getting and after success full result put this value in salary filed using jQuery function
I have 2 separate dropdown lists. I need to get each dropdown to filter each other. Every example I have seen so far is an example for dropdowns that have the options hard-coded in. Mine uses a query to populate the options.
So how could I correctly have each dropdown menu filter each other?
Here is my HTML for the dropdowns on index.php:
<select id="collector" onchange="showUser(this.value)">
<option value="" selected disabled>Collector Name</option>
<?php foreach($collect->fetchAll() as $name) { ?>
<option class="<?php echo $name['Collector Name'];?>" value="<?php echo $name['Collector Name'];?>"><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
<select id="date" onchange="showUser(this.value)">
<option value="" selected disabled>Bill Date</option>
<?php foreach($bill_date->fetchAll() as $date) { ?>
<option class="<?php echo $date['Date'];?>" value="<?php echo $date['Collector Name'];?>"><?php echo $date['Date'];?></option>
<?php } ?>
</select>
Code that runs each time the dropdown is changed in script tags on index.php:
function showUser(str) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
var newTableObject = document.getElementById('billing_table');
sorttable.makeSortable(newTableObject);
}
}
// ---- Gets value of collector dropdown selection -----
var e = document.getElementById("collector").value;
$.ajax({
type: 'GET',
url: 'index.php',
data: e,
success: function(response) {
console.log(e);
}
});
// ---- Gets value of the current selection in any of the dropdowns ----
xmlhttp.open("GET","dropdown-display.php?q="+str,true);
xmlhttp.send();
document.getElementById('billing_table').style.display = 'none';
}
$(document).ready(function(){
var $select1 = $( '#collector' ),
$select2 = $( '#date' ),
$options = $select2.find( 'option' );
$select1.on( 'change', function() {
$select2.html( $options.filter( '[value="' + this.value + '"]' ) );
}).trigger( 'change' );
});
Query on my index.php page:
$collector = "SELECT [Collector Name]
FROM [vSpecial_Billing]
Group By [Collector Name]";
$billdate = "SELECT [Collector Name], [Date]
FROM [vSpecial_Billing]
Group By [Collector Name], [Date]";
I don't want to send the value to my dropdown-display.php page since my queries that populate the dropdowns are on my index.php page. However, if I put the value variable in the query, then it runs that query on load before a collector selection can be made and my bill date dropdown will then not be populated.
EDIT:
I changed the value in the options for the date dropdown to Collector Name instead of Date
I also added the $(document).ready(function() at the end of the middle block of code
I updated the queries that I am using
It filters correctly now, however, on page load, the bill date is unable to selected. It is not populated with any rows. How can I change this?
Also, when I filter it, it defaults to the last date on the list. How can I get it to default to a hardcoded value such as "Date" and then the user can select from the filtered values?
I wrote up a test case, using some example data, and made sure this works. Its a rough example, but I believe its doing what you need. With a lot less cruft in the works. I'm sorry, but I used full jquery, because I cannot be bothered to do long-hand javascript anymore haha (plus I couldn't really follow what you had going on in there).
There will need to be two files: index.php and index-ajax.php (for clarity)
index.php brief:
// note: these do not need to be in prepared statements (theres no variables inside)
$collect = $db->query("SELECT DISTINCT [Collector Name] FROM [vSpecial_Billing]");
$names = $collect->fetchAll();
$billdate = $db->query("SELECT DISTINCT [Date] FROM [vSpecial_Billing]");
$dates = $billdate->fetchAll();
?>
<form id="testForm" action="">
<select id="collector">
<option value="" selected="selected" disabled="disabled">Collector Name</option>
<?php foreach($names as $name) { ?>
<option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
<select id="date">
<option value="" selected="selected" disabled="disabled">Bill Date</option>
<?php foreach($dates as $date) { ?>
<option class="choice" value="<?php echo $date['Date'];?>"><?php echo $date['Date'];?></option>
<?php } ?>
</select>
<input type="button" id="clearchoices" name="clearchoices" value="Clear Choices" />
</form>
Some things to note in the above:
You only need to select by DISTINCT. No need to do GROUP BY to get all unique names, or all unique dates.
I put the results of fetchAll into variables, out of habit, but you can move them into the foreach if you wish.
I removed the class defines you had, because a class with spaces in it (in the case of a Collector Name) can be buggy.
The Clear Choices button is just an example of how to reset those selects after they get filtered and filtered beyond what you can select.
This is the javascript portion (it goes in index.php before or after your form, or in the head):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="Javascript" type="text/javascript">
$(document).ready(function(){
$("#collector").change(function(e){
$.post('index-ajax.php',{filter:'Name',by:$(this).val()},function(data){
$("#date .choice").hide();
$.each(data, function(key,row) {
// $("#date option[value='"+ row.item +"']").show();
$("#date option").filter(function(i){
return $(this).attr("value").indexOf( row.item ) != -1;
}).show();
});
},"JSON");
});
$("#date").change(function(e){
$.post('index-ajax.php',{filter:'Date',by:$(this).val()},function(data){
$("#collector .choice").hide();
$.each(data, function(key,row) {
// $("#collector option[value='"+ row.item +"']").show();
$("#collector option").filter(function(i){
return $(this).attr("value").indexOf( row.item ) != -1;
}).show();
});
},"JSON");
});
$("#clearchoices").click(function(e){ e.preventDefault();
$("#collector .choice").show(); $("#collector").val('');
$("#date .choice").show(); $("#date").val('');
});
});
</script>
That block needs a lot of explaining, because I took all your long-hand javascript and packed it into jquery.
Each select has its own handler event for when it changes.
Each select does its own post ajax, with a different variable define to filter on.
After the ajax returns, it hides all options in the OTHER select. Then enables all options which are returned by the json data of the ajax call. This could be handled differently, but I wanted to present one way of doing it.
A key thing is setting "JSON" for the return handler of the .post() methods. You'll see why in index-ajax.php.
And now the index-ajax.php:
if (isset($_POST['filter']) and isset($_POST['by'])) {// sanity check
$results = array();
if (!empty($_POST['by'])) {
// these _DO_ need to be in prepared statements!!!
if ($_POST['filter'] == 'Name') { $sql = "SELECT DISTINCT [Date] as item FROM [vSpecial_Billing] WHERE [Collector Name] = ?"; }
if ($_POST['filter'] == 'Date') { $sql = "SELECT DISTINCT [Collector Name] as item FROM [vSpecial_Billing] WHERE [Date] = ?"; }
$stmt = $db->prepare($sql);
$stmt->execute(array($_POST['by']));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $results[] = $row; }
}
echo json_encode( $results );
exit;
}
This bit of code is actually pretty straightforward. All it does is determine which filter operation to do, prepares the sql, and then grabs distinct matching rows for output. The key thing though is it outputs as json, so the javascript that called this can handle the data easier!
Now... I had built all this in a test script, and my server hates "fetchAll", so your milage may vary on some of the DB code. I also left out all other form code and db setup handlers and all that. Figuring you have a handle on that.
I hope this helps you out, in some way or other.
EDIT 11/7
I made a slight change because I didn't realize the Collector Names in your db would have characters that would break all of this, oops. Two changes for odd character handling:
The select for collector has its option values wrapped in htmlspecialchars().
The jquery portion for where each select .change event filters, is now filtering by looking for a matching index, using the row.item as a direct variable. Before, it was using it in a value=' row.item ' match, which if the row.item had single quotes (or other bad chars), it would break the whole js event and fail!
Generally when I setup things like this, I use ID's and unique element id tags. That way I am only ever referencing by numbers, and wont run into odd character mash. An example of switching everything to ID's would be involved, and I think you have the gist of whats going on now.
I have a HTML form along with a script, which automatically triggers the default "option" (option values hard-coded).
I also have a stand-alone script, which creates the choices of "options" dynamically, based on a specific column values in MySQL.
Problem: When selecting from the drop-down list from the dynamically generated list, it does not "trigger" anything (nor manual, nor automatic, manual would be just fine in this case)
The form which auto-triggers the default "option":
<form>
<select name="fruit" onchange="showFruit(this.value)">
<option>Choice:</option>
<option value="1">Yellow Fruit</option>
<option value="2">Red Fruit</option>
</select>
</form>
<script>
window.onload = function () {
var el = document.getElementsByName('fruit')[0];
el.value = 1; //Set default value
el.onchange(); //trigger onchange event
}
function showFruit(val) {
alert(val);
}
</script>
And the code which generates the dynamically created "options" list from a specific MySQL column:
<? $connect = mysqli_connect('localhost', '*', '*', '*');
$sql="SELECT DISTINCT(fruit_name) AS fruit_name FROM fruit ORDER BY fruit_name ASC";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0){
$select= '<select name="select">';
while($rs = mysqli_fetch_array($result)){
$select.='<option value="'.$rs['id'].'">'.$rs['fruit_name'].'</option>';
}
}
$select.='</select>';
echo $select;
How can I have the onload function to attach to the dynamically generated "options" list? I donĀ“t need any hard-coded "options" at all. Just the dynamically generated one. And when I select from the list, I would like to get a response/reaction of any sorts.
I would probably keep them separated for clarity of purpose and include your template file into your logic file that does the work of formatting the data for the page. By gating the select menu behind a conditional you can make sure it only renders when you have data to put in it.
I formatted this in a particular way, that you don't need to follow but it is fairly good practice to pick a consistent style and stick to it throughout. I also updated your usage of the mysqli class to the object oriented approach. Be aware that in this case you aren't vulnerable to sql injection while using Mysqli->query, but if you are planning on taking user input you should study prepared statements to prevent sql injection.
practically I use the <?= ?> operator in the template file this is a shorthand for <?php echo '';?>, use of <? as your php file opener is discouraged <?php is standard.
PHP also allows for short open tag <? (which is discouraged since it is only available if enabled using the short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option).
When mixing PHP and HTML usually its more clear (opinion!) to use the alternative if and loop syntax where possible (the <?php if () : ?> <?php endif; ?> rather than <?php if () { ?> <?php } ?>) but both work
Logic File
<?php
// page.php
$display = false;
$mysqli = new mysqli(HOST, USER, PASSWORD, SCHEMA);
$sql = "SELECT DISTINCT(fruit_name) AS fruit_name FROM fruit ORDER BY fruit_color ASC";
$result = mysqli->query($sql);
// not sure this is necessary in this particular case, but
if ($result->num_rows > 0) {
$display = true;
$select = []
while ($row = $result->fetch_assoc()) {
$select[] = "<option value=\"{$row['id']}\">{$row['fruit_name']}</option>";
}
}
include 'htmlfile.php';
?>
Template File
<!-- htmlfile.php -->
<form>
<?php if ($display) : ?>
<select name="select">
<?= implode('', $select) ?>
</select>
<?php endif; ?>
</form>
<script>
window.onload = function () {
var el = document.getElementsByName('fruit')[0];
el.value = 1; //Set default value
el.onchange(); //trigger onchange event
}
function showFruit(val) {
alert(val);
}
</script>
Hi I need to populate a dropdown field using a value taken from the database and show it as selected and at the same i would like to show a list of options taken from the database,
Everything works fine except for the field "User Group" this is what i've done so far, can anybody please help me?
Many thanks
Html file
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">User Group
<span class="required"> * </span>
</label>
<select class="form-control bs-select" id="userGroup" name="userPippo">
<?php
$select_group_query="SELECT group_id, group_name FROM user_group";
$run= mysqli_query($conn, $select_group_query);
while($row= mysqli_fetch_array($run)) {
echo "<option value= '".$row['group_id']."' >" . $row['group_name'] . "</option>";
}
?>
</select>
</div>
</div>
</div>
Javascript file
function GetUserDetail(id) {
$("#EditUserModal").modal("show");
$("#user_id").val(id);
var user_id = $('#user_id').val();
$.ajax({
url: "../controllers/ctrl_admin_user_app/ctrl_admin_get_user_details.php",
method: "POST",
data: {
user_id: user_id
},
dataType: "json",
success: function(data) {
console.log(data);
$('#firstName').val(data.user_first);
$('#lastName').val(data.user_last);
$('#userEmail').val(data.user_email);
$('#userTel').val(data.user_telephone);
$('#userFiscalcode').val(data.user_fiscalcode);
$('#userBirth').val(moment(data.user_birth).format('DD/MM/YYYY'));
$('#userDocument').val(data.user_iddocument);
$('#userRole').val(data.user_role);
// ricarico il campo per falo funzionare con il plugin bs-select
$('#userRole').selectpicker('refresh');
$('#userGroup').val(data.group_name); // doesn't work
// make it work with bs-select
$('#userGroup').selectpicker('refresh');
doesn 't work
$("#EditUserModal").modal("show");
}
});
}
PHP File
if (isset($_POST["user_id"])) {
$userid = $_POST['user_id'];
$user_id = filter_var($userid, FILTER_SANITIZE_NUMBER_INT);
$query = "SELECT group_id, group_name, user_first, user_last, user_email, user_telephone, user_fiscalcode, user_birth, user_iddocument, user_role FROM user_group_join LEFT JOIN (user_group, users) ON (user_group_join . group_join_id = user_group . group_id AND user_group_join . user_join_id = users . user_id) WHERE user_join_id = ? ";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "i", $user_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$response = array();
while ($row = mysqli_fetch_assoc($result)) {
$response = $row;
}
echo json_encode($response);
}
from the Documentation,
.selectpicker('val');
You can set the selected value by calling the val method on the element.
$('.selectpicker').selectpicker('val', 'Mustard');
$('.selectpicker').selectpicker('val', ['Mustard','Relish']);
This is different to calling val() directly on the select element. If you call val() on the element directly, the bootstrap-select ui will not refresh (as the change event only fires from user interaction). You will have to call the ui refresh method yourself.
.selectpicker('refresh');
To programmatically update a select with JavaScript, first manipulate the select, then use the refresh method to update the UI to match the new state. This is necessary when removing or adding options, or when disabling/enabling a select via JavaScript.
$('.selectpicker').selectpicker('refresh');
So,
Replace these lines
$('#userGroup').val(data.group_name); // doesn't work
// make it work with bs-select
$('#userGroup').selectpicker('refresh');
with this line,
$('#userGroup').selectpicker('val', data.group_id).selectpicker('refresh');
I need help with generating dynamic dropdowns using PHP, Javascript and mySQL. I am not good with AJAX and Javascript and hence I'm asking for help here.
I have a table named Hotel, which contains a list of hotel names and categories. They are categorised by locations such as North, South, East and West. I am trying to allow the user to pick the categories they want, then the second dropdown will generate a list of available hotels under that particular category. As mentioned, I am not good with AJAX or JS.
The question has been solved! I have edited my answer to work with the database, assuming basic user root and no password. the table hotel has 3 columns, id, category and name.
booking.php
<div class="form-group">
<label class="control-label col-sm-3" for="PreferredHotel">Preferred Hotel:</label>
<div class="col-sm-3">
<select class="form-control" name="hotelCategory" onchange="fetchHotelNameByArea(this.value)">
<option value="0">Please select area above first</option>
<?php
mysqli_select_db($dbConn, $database_dbConn);
$query_hotelselect = "SELECT * FROM hotel GROUP BY Category";
$hotelselect = mysqli_query($dbConn, $query_hotelselect) or die(mysqli_error($dbConn));
$row_hotelselect = mysqli_fetch_assoc($hotelselect);
while ($row_hotelselect = mysqli_fetch_assoc($hotelselect)) {
echo "<option value='" . $row_hotelselect['Category'] . "'> " . $row_hotelselect['Category'] . " </option>";
}
?>
</select>
<?php
echo $row_hotelselect;
?>
</div>
<div class="col-sm-3" id="fetchHotelNameByAreaResult">
<select class="form-control">
<option value="0">Please select area above first</option>
</select>
</div>
<script>
function fetchHotelNameByArea(HotelArea) {
//above (HotelArea) are actually the value (this.value) in the form which will be what the user select (North, South, East or West)
var xhttp = new XMLHttpRequest();
var url = "getter.php";//<- just a sample url
var data = new FormData();
//below will "assign HotelArea to $_POST['SearchValue']"
data.append('SearchValue', HotelArea);
xhttp.open('POST', url, true);
xhttp.send(data);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("fetchHotelNameByAreaResult").innerHTML = xhttp.responseText;
}
}
}
</script>
</div>
getter.php
<?php
if ($_POST['SearchValue']) {
$searchname = $_POST['SearchValue'];
require_once('Connections/dbConn.php');
mysqli_select_db($dbConn, $database_dbConn);
$query_preferredhotel = "SELECT * FROM hotel WHERE Category = '$searchname'";
$preferredhotel = mysqli_query($dbConn, $query_preferredhotel) or die("Could not select examples");
$row_preferredhotel = mysqli_fetch_assoc($preferredhotel);
echo'<select class="form-control" name="preferredHotel">';
while ($row_preferredhotel = mysqli_fetch_assoc($preferredhotel)) {
echo "<option value='" . $row_preferredhotel['Name'] . "'> " . $row_preferredhotel['Name'] . " </option>";
}
}echo '</select>';
?>
Kinda got stuck here after making the dropdown list appear. I found an article on https://css-tricks.com/dynamic-dropdowns/ but they do not have the example for the database and I was hoping someone could help me with this as I understand I would most likely need AJAX to request for data from the database/server and populate the second dropdown. Im not asking for spoonfeeding, but I really have very little clues about AJAX. Any guidance would be helpful!
EDITED
The issue with only part of the keywords being passed has been solved, thanks to Mark Ng spotting my markup error! I am really thankful for all your help in answering my questions, thank you!
sample concept.
There are 2 select(dropdown), the first will populate the second based on its category.
1st select
<select onchange="fetchHotelNameByArea(this.value)">
<option value="North">North</option>
<option value="South">South</option>
<option value="East">East</option>
<option value="West">West</option>
</select>
2nd select(to be populated by javascript later)
<div id="fetchHotelNameByAreaResult">
<!--For temporary only, this select was purposely placed inside this div id, it will get re-written by javascript when result are generated-->
<select>
<option value="0">Please select area above first</option>
</select>
</div>
JS(Native)
<script>
function fetchHotelNameByArea(HotelArea) {
//above (HotelArea) are actually the value (this.value) in the form which will be what the user select (North, South, East or West)
var xhttp = new XMLHttpRequest();
var url = "./php/find_hotel_name_by_area.php";//<- just a sample url
var data = new FormData();
//below will "assign HotelArea to $_POST['SearchValue']"
data.append('SearchValue',HotelArea);
xhttp.open('POST',url,true);
xhttp.send(data);
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("fetchHotelNameByAreaResult").innerHTML = xhttp.responseText;
}
}
}
</script>
php query (The select will be returned to div id="fetchHotelNameByAreaResult" by javascript
<?php
if($_POST['SearchValue']) {
$searchname = $_POST['SearchValue']
//.... your query
//"SELECT * FROM hotel WHERE Category = '$searchname'";
echo '<select class="blablabla">';
while ($row_hotelselect = mysqli_fetch_assoc($hotelselect)) {
echo "<option value=" . $row_hotelselect['id'] . "> " . $row_hotelselect['Name'] . " </option>";
}
}
echo '</select>';
?>
What is going on?
1. Upon 1st select, the onchange gets fired, calling function fetchHotel...
2. JS send data to server, where a php file will process the request, onreadystate... will detect if response is ready, and innerHTML will re-write whatever is in div id="fetchHotelNameByAreaResult" with the resposeText generated by the php script.
There are other ways to do it via jQuery, etc. But once you get the basic concept, you are ready to move on.
EDIT to address this issue.
Hey there again, the codes above works fine. But however, I realised
that the dropdown list only passes one part of the value inside the
variable (eg. ritz carlton, only passes ritz to the next form). Anyone
aware of any solutions?
There is a html markup error.
echo "<option value=" . $var . ">" . $var . "</option>";
//The above will return <option value=ritz carlton>ritz carlton</option> in html.
//the problem lies with value=ritz carlton as there is a space in between.
//html will think that it is value="ritz" while carlton is not a valid attribute, it will simply ignore it and only set the value as ritz, so only the value ritz was posted.
//In order to get the full string parse, you have to quote them like below.
echo "<option value='". $var ."'>" . $var . "</option>";
// echo "<option value=" . "'" . $var . "'" . "</option>";
// echo "<option value=/" " . $var . " /"</option>";
//a lot more ways to achieve same result.
//These will return <option value="ritz carlton">ritz carlton</option> in html. This will set the value as ritz carlton and the value "ritz carlton" will be posted.
?>
I read your question and understood your problem.
Basic steps :
First create a section behind your first drop down in which hotel name will be fetched according to the category selected in first drop down.
Example :
<div class = "hotelDropDown">
// hotel drop down
</div>
After, create an ajax request that will fetch the category name from first drop down and will send the request to the php file to fetch the hotel name correspinding to the selected category name and make the drop down.
Example :
$.ajax({
url : "hotelfetch.php",// function to create hotel dropdown
data : {categoryName : $('.hotelCategory').val()}
success :
function(data){
//generate dropdown of hotel name
});
});
Make a view file of hotelfetch.php in which you create a dropdown of hotel name according to fetched category name and replace it in the html of the section created below category drop down which I created for you.