not displaying selected options in drop down menu - php

Below I have a piece of code where it is suppose to display 2 drop down menus, one for building and other for rooms. What happens is when the user selects a building from the building drop down menu, using the ajax/jquery it will navigate to the room.php page and lists the rooms that belongs to the building selected and displays the list of rooms in the rooms drop down menu. This works fine:
<script type="text/javascript">
function getRooms() {
var building = jQuery("#buildingsDrop").val();
jQuery('#roomsDrop').empty();
jQuery('#roomsDrop').html('<option value="">Please Select</option>');
jQuery.ajax({
type: "post",
url: "room.php",
data: { building:building },
success: function(response){
jQuery('#roomsDrop').append(response);
}
});
}
</script>
...
<?php
$sql = "SELECT DISTINCT Building FROM Room";
$sqlstmt=$mysqli->prepare($sql);
$sqlstmt->execute();
$sqlstmt->bind_result($dbBuilding);
$buildings = array(); // easier if you don't use generic names for data
$buildingHTML = "";
$buildingHTML .= '<select name="buildings" id="buildingsDrop" onchange="getRooms();">'.PHP_EOL;
$buildingHTML .= '<option value="">Please Select</option>'.PHP_EOL;
while($sqlstmt->fetch())
{
$building = $dbBuilding;
$buildingHTML .= "<option value='".$building."'>" . $building . "</option>".PHP_EOL;
}
$buildingHTML .= '</select>';
$roomHTML = "";
$roomHTML .= '<select name="rooms" id="roomsDrop">'.PHP_EOL;
$roomHTML .= '<option value="">Please Select</option>'.PHP_EOL;
$roomHTML .= '</select>';
?>
room.php:
$building = isset($_POST['building']) ? $_POST['building'] : '';
$sql = "SELECT Room FROM Room WHERE Building = ?";
$sqlstmt=$mysqli->prepare($sql);
$sqlstmt->bind_param("s",$building);
$sqlstmt->execute();
$sqlstmt->bind_result($dbRoom);
$roomHTML = "";
while($sqlstmt->fetch()) {
$roomHTML .= "<option value='".$dbRoom."'>" . $dbRoom . "</option>".PHP_EOL;
}
echo $roomHTML;
The problem I am having though is the when a user selects an assessment, it is suppose to display the assessment's building and room options in the relevant drop down menus. But it is not selecting those options, they remain on the "Please Select" option. Why is this and how can I get the options shown?
Below is the view source code:
//Assessment drop down menu:
<p><strong>Assessments:</strong> <select name="session" id="sessionsDrop">
<option value="">Please Select</option>
<option value='71' style='color: green'>AKXMB - 30-11-2012 - 10:00</option>
</select> </p>
</form>
//Building drop down menu:
<select name="buildings" id="buildingsDrop" onchange="getRooms();">
<option value="">Please Select</option>
<option value='Canalside East'>Canalside East</option>
<option value='Canalside West'>Canalside West</option>
</select>
//Room drop down menu (list of rooms displayed in room.php):
<select name="rooms" id="roomsDrop">
<option value="">Please Select</option>
</select>
//Retrieve assessment information
//(Below is where problem lies where it is not selecting building and room options in drop down menu)
<script type="text/javascript">
$(document).ready( function(){
var sessioninfo = [{"SessionId":71,"Building":"Canalside East","Room":"CE01\/04"},{"SessionId":84,"Building":"Canalside East","Room":"CE01\/04"}];
$('#sessionsDrop').change( function(){
var sessionId = $(this).val();
if (sessionId !== '') {
for (var i = 0, l = sessioninfo.length; i < l; i++)
{
if (sessioninfo[i].SessionId == sessionId) {
var currentbuilding = $('#currentBuilding').val(sessioninfo[i].Building);
var editbuilding = $('#BuildingsDrop').val(sessioninfo[i].Building);
var currentroom = $('#currentRoom').val(sessioninfo[i].Room);
var editroom = $('#RoomsDrop').val(sessioninfo[i].Room);
var currentid = $('#currentId').val(sessioninfo[i].SessionId);
var editid = $('#newId').val(sessioninfo[i].SessionId);
break;
}
}
}
});
});
</script>
UPDATE:
Application
In the application select a "Module" from drop down menu and submit.
Below it should show some features. In the Assessment drop down menu
select any assessment.
You can see underneath that for "Current Assessment Details" it
displays the building and room in the readonly text inputs to
indicate what is the assessment's current building and room.
I want the same building and room to be selected in the drop down
menus in the "New Assessment's Room" section. You can see the
building is selected in the Building drop down menu but the Room is
not selected in the Room drop down menu.

Unless this was a copy/paste error, you are missing your <script></script> tags around your assessment function/script -
<script type="text/javascript">
$(document).ready( function(){
...
});
</script>
Edit
Your issue is that your id's are wrong case -
...
var editbuilding = $('#BuildingsDrop').val(sessioninfo[i].Building);
...
var editroom = $('#RoomsDrop').val(sessioninfo[i].Room);
Change to -
...
var editbuilding = $('#buildingsDrop').val(sessioninfo[i].Building);
...
var editroom = $('#roomsDrop').val(sessioninfo[i].Room);
see also - In the DOM are node ids case sensititve?
Edit - 2
Just add getRooms() just before var editroom to populate #roomsDrop so then you can set the selected.
var currentbuilding = $('#currentBuilding').val(sessioninfo[i].Building);
var editbuilding = $('#buildingsDrop').val(sessioninfo[i].Building);
var currentroom = $('#currentRoom').val(sessioninfo[i].Room);
getRooms();
var editroom = $('#roomsDrop').val(sessioninfo[i].Room);
var currentid = $('#currentId').val(sessioninfo[i].SessionId);
var editid = $('#newId').val(sessioninfo[i].SessionId);
Edit - 3
By default, $.ajax runs asynchronously in the browser, so the issue is that before your are getting to success: function(response){} in function getRooms() it has already moved on to var editroom = $('#roomsDrop').val(sessioninfo[i].Room);, and since jQuery('#roomsDrop').append(response); has not appended the option values to roomsDrop there is nothing to select. This can be fixed in 2 ways -
(1) quick fix using async: false
<script type="text/javascript">
function getRooms() {
var building = jQuery("#buildingsDrop").val();
jQuery('#roomsDrop').empty();
jQuery('#roomsDrop').html('<option value="">Please Select</option>');
jQuery.ajax({
type: "post",
url: "room.php",
data: { building:building },
async: false,
success: function(response){
jQuery('#roomsDrop').append(response);
}
});
}
</script>
This makes the $.ajax call synchronously, so it will not proceed to var editroom = $('#roomsDrop').val(sessioninfo[i].Room); until after the success: function(response){} is done. note be aware that async: false freezes the browser while it waits for the response, so it may hold up any other actions.
(2) using a callback function -
<script type="text/javascript">
function getRooms(callback) {
var building = jQuery("#buildingsDrop").val();
jQuery('#roomsDrop').empty();
jQuery('#roomsDrop').html('<option value="">Please Select</option>');
jQuery.ajax({
type: "post",
url: "room.php",
data: { building:building },
async: false,
success: function(response){
jQuery('#roomsDrop').append(response);
callback();
}
});
}
</script>
AND
getRooms(function(){
var editroom = $('#roomsDrop').val(sessioninfo[i].Room);});
This callback function will execute the var editroom = $('#roomsDrop').val(sessioninfo[i].Room); after getRooms() has finished, but will continue the rest of the script without holding up the browser

Related

Optgroup issue in jquery

Actually I have main categories under main categories I have list of products. For first main category I have subcategory and subcategory related products. whichever main category is not having subcategories I am splitting array with comma separator and appending that products to select dropdown. But if main category is having subcategory means I need to do optgroup with options. In optgroup subcatname and related products.
For example, subcatname1=> p1,p2,p3, subcatname2=> p1,p2,p3.
How we can resolve this please help somebody.
Below is HTML,
<select name="category" id="category" />
<option selected ="selected">Select category</option>
<?php foreach($decode as $key => $value) { ?>
<option value="<?php echo $value['category_id']; ?>"><?php echo $value['name']; ?></option>
<?php } ?>
</select>
<select name="category12" class="category12" /></select>
Below is Jquery,
$(document).ready(function(){
$('#category').change(function(){
var category_id=$('#category').val();
$.ajax({
type: "get",
url: 'data_product.php?category_id='+category_id,
success: function(data) {
var products = data.split(",");
state_html = '';
state_html = '<option>Please Select product</option>'
$.each(products, function (index, productName) {
state_html += "<option value='"+productName+"'>"+productName+"</option>";
//var gain=
});
$('.category12').html(state_html);
},
$.each(data, function (index, sub_cat_name) {
state_html += "<optgroup label='"+sub_cat_name+"'>"+sub_cat_name+"
<option value="+products_name+">"+products_name+"</option>
</optgroup>";
//var gain=
});
$('.category12').html(state_html);
},
});
})
});
You should iterate only once for your data and split the productnames from it.
Try the below code,
$(document).ready(function() {
$('#category').change(function() {
var category_id = this.value; // use simply this.value here
$.ajax({
type: "get",
url: 'data_product.php?category_id=' + category_id,
dataType:'json',
success: function(data) {
state_html = '<option>Please Select product</option>'
$.each(data, function(sub_cat_name, product) {
// split all products here
var products = product.split(",");
make optgroup from sub_cat_name key
state_html += "<optgroup label='" + sub_cat_name + "'>" + sub_cat_name;
// loop for all product options
for (var i = , l = products.length; i < l; i++) {
state_html += "<option value='" + products[i] + "'>" + products[i] + "</option>";
}
state_html += "</optgroup>"; // close optgroup here
});
// finally append all options
$('.category12').html(state_html);
}
});
})
});

Autofill a select after submission via jQuery

I've got a form where users can choose a car brand. After that I send an SQL-query with Ajax to fill the next select with all the models of the selected brand.
When the form is submited I check it via PHP and if there is any error I return to the previous form with an error-message and fields filled.
The problem is that the 'model' field has the "trigger" set on brand change.
How can I fix this: call the jquery again (to show the models in the select) and display the previous model as selected?
Ajax.php
if ($_POST['brand_car']) {
$sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
$req = $dbh->prepare($sql);
$req->bindValue(':idBrand', $_POST['brand_car']);
$req->execute();
$model = array();
foreach ($req as $row){
$model[] = array(
'id' => $row['id_model_car'],
'modele' => $row['name_model_car']
);
}
echo json_encode($model);
}
jQuery
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
if(id!=0)
$.ajax({
url: '/js/ajax.php',
dataType: 'json',
type: "POST",
data: {brand_car: id},
success: function(data){
$('#model_car').html('<option id="0" value="">choose the model</option>');
if (data.length > 0) {
data.forEach(function (elem) {
$('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
});
}}
});
});
XHTML + PHP
<select id="brand_car" name="brand_car">
<?php
$sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
$req = $dbh->query($sql);
foreach ($req as $row) {
$val=$row['id_brand_car'];
echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
echo ' >'.$row['nom_brand_car'].'</option>';
}
?>
</select>
<select id="model_car" name="model_car">
<option></option>
</select>
There are various ways you can fix it.
jQuery Approach
I think the simplest way is to refractor your change() and seperate the ajax call from the change event, like so:
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
getModels(id, 0);
}
function getModels(id, select) {
if(id!=0)
$.ajax({
url: '/js/ajax.php',
dataType: 'json',
type: "POST",
data: {brand_car: id},
success: function(data){
$('#model_car').html('<option id="0" value="0">choose the model</option>');
if (data.length > 0) {
data.forEach(function (elem) {
$('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
});
$('#model_car').val(select);
}}
});
}
This allows you to make an AJAX call by calling getModels(). So all you have to do is call it:
<select id="brand_car" name="brand_car">
<?php
$sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
$req = $dbh->query($sql);
foreach ($req as $row) {
$val=$row['id_brand_car'];
echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
echo ' >'.$row['nom_brand_car'].'</option>';
}
?>
</select>
<select id="model_car" name="model_car">
<option></option>
</select>
Tag this at the end:
<?php
echo '<script>getModels('.$_SESSION["brand_car"].', '.$_SESSION['model_car'].');</script>';
?>
This way the code is also more testable. This isn't a perfect solution and you should definitely consider using $(function(){}); to make sure the document is ready. AJAX request also needs time to complete, so that models won't be there instantaneously when the page loads.
PHP Approach
Alternatively, you could consider reusing your AJAX code. Wrap it into a function:
function getModels($dbh, $brand_car) {
// I know nothing about your design, but globals are no good
$sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
$req = $dbh->prepare($sql);
$req->bindValue(':idBrand', $brand_car);
$req->execute();
$model = array();
foreach ($req as $row){
$model[] = array(
'id' => $row['id_model_car'],
'modele' => $row['name_model_car']
);
}
return $model;
}
AJAX.php
if ($_POST['brand_car']) {
echo json_encode(getModels($dbh, $_POST['brand_car']));
}
In your XHTML + PHP
<select id="model_car" name="model_car">
<?php
foreach(getModels($dbh, $_SESSION["brand_car"]) as $model) {
echo '<option name="'.$model["id"].'" id="'.modelp["id"].'">'.$model["modele"].'</option>';
}
?>
</select>
PS. It looks like your $_SESSION['brand_car'] is never updated.

Getting value from dynamically created pop up menu

I have a menu that is dynamically created. When the user selects a value, I need to get that value and use it for a query statement. This is not a form, just a menu on the page.
I have:
<select name="topic" id="topic">
<option value="optiont" selected="selected">Select topic...</option>
<?php
while ($row = mysqli_fetch_array($sql))
{
echo "<option value=\"optiont$count\" name=\topic[]\">" . $row['topic'] . "</option>";
$count++;
}
?>
</select>
I want to know which option is selected. How can I do this??
This will get the value when you change the DDL:
$('#topic option').on("change", function () {
var opt_ID = $(this).val();
//Do something here using opt_ID as the value e.g.
window.location = '/URL/file.php?' + opt_ID;
});
Try this:
jquery:
var selvalue = $("#topic option:selected").val();
$.get( "demo.php?value="+selvalue, function(data) {
alert(data);
});
Demo.php:
<?php
$sel = $_GET['value'];
// write your query here
?>

Having ajax trouble when it comes to displaying a selected option

I am terribly failing with an ajax/jquery piece of code I am trying to learn in order to solve a predicament I have.
Below is my ajax:
$('#sessionsDrop').change( function(){
var search_val = $(this).val();
$.post("addstudentsession.php",
{studenttextarea : search_val},
function(data){
if (data.length>0){
$("#studentselect").html(data);
}
});
At the moment I am keeping getting a blank page everytime I load my addstudentsession.php script. This is the only script I am working on so I am not sure if I am suppose to link the ajax to itself. But below is what I am trying to do:
I have a drop down menu below:
<select name="session" id="sessionsDrop">
<option value="">Please Select</option>
<option value='20'>EWYGC - 10-01-2013 - 09:00</option>
<option value='22'>WDFRK - 11-01-2013 - 10:05</option>
<option value='23'>XJJVS - 12-01-2013 - 10:00</option>
<option value='21'>YANLO - 11-01-2013 - 09:00</option>
<option value='24'>YTMVB - 12-01-2013 - 03:00</option>
</select> </p>
Below I have a Multiple Select box where it displays a list of students that is taking the select assessment from the drop down menu above:
$studentactive = 1;
$currentstudentqry = "
SELECT
ss.SessionId, st.StudentId, st.StudentAlias, st.StudentForename, st.StudentSurname
FROM
Student_Session ss
INNER JOIN
Student st ON ss.StudentId = st.StudentId
WHERE
(ss.SessionId = ? and st.Active = ?)
ORDER BY st.StudentAlias
";
$currentstudentstmt=$mysqli->prepare($currentassessmentqry);
// You only need to call bind_param once
$currentstudentstmt->bind_param("ii",$sessionsdrop, $stuentactive);
// get result and assign variables (prefix with db)
$currentstudentstmt->execute();
$currentstudentstmt->bind_result($dbSessionId,$dbStudentId,$dbStudentAlias,$dbStudentForename.$dbStudentSurname);
$currentstudentstmt->store_result();
$studentnum = $currentstudentstmt->num_rows();
$studentSELECT = '<select name="studenttextarea" id="studentselect" size="6">'.PHP_EOL;
if($studentnum == 0){
$studentSELECT .= "<option disabled='disabled' class='red' value=''>No Students currently in this Assessment</option>";
}else{
while ( $currentstudentstmt->fetch() ) {
$studentSELECT .= sprintf("<option disabled='disabled' value='%s'>%s - %s s</option>", $dbStudentId, $dbStudentAlias, $dbStudentForename, $dbStudentSurname) . PHP_EOL;
}
}
$studentSELECT .= '</select>';
But I have a little problem, I need a way to be able to display the list of students in the select box when the user has selected an option from the drop down menu. The problem with the php code is that the page has to be submitted to find its results.
So that is why I am trying to use ajax to solve this but what am I doing badly wrong?
Try using ajax call as following,
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
XMLHttpRequestObject = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
XMLHttpRequestObject = false;
}
}
}
$('#sessionsDrop').change( function(){
var search_val = $(this).val();
if (XMLHttpRequestObject) {
XMLHttpRequestObject.open("POST", "addstudentsession.php", true);
XMLHttpRequestObject.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
}
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4
&& XMLHttpRequestObject.status == 200) {
y = XMLHttpRequestObject.responseText;
$("#studentselect").html(y);
}
};
};
XMLHttpRequestObject.send("studenttextarea=" + search_val);

Populate select with jQuery and PHP

I have a table that includes the taxonomic name of a species. So there are separate columns for each species, domain, kingdom, phylum, etc. I am using a select boxes for each of these classifications, and what I need to happen is when the first one (Domain) is selected, the database is queried to get all the kingdomes where domain is the value of the previous select.
Here's what I have for my PHP in 'search.php':
<select name="domain" id="domain">
<option value="standard">-- Domain --</option>
<?php while($row = mysql_fetch_array($get_domains, MYSQL_NUM))
{
echo "<option value='$row[0]'>$row[0]</option>";
} ?>
</select>
<select name="kingdom" id="kingdom" >
<option value="standard">-- Kingdom --</option>
<?php
$result = array();
$domain = $_POST['domain'];
$get_kingdoms = mysql_query("SELECT DISTINCT sci_kingdom FROM tbl_lifedata WHERE sci_domain = $domain");
while($row = mysql_fetch_array($get_kingdoms, MYSQL_NUM))
{
$result[] = array(
'name' => $row[0]
);
}
echo json_encode($result);
?>
</select>
And this is what I have in my jquery:
$('#domain').change(function() {
$domain = $('#domain option:selected').val();
if ($domain == 'standard') {
$('#kingdom').attr('disabled', 'disabled');
$('.btn-cover').text('Select a Domain:');
} else {
$('#kingdom').removeAttr('disabled', 'disabled');
$('.btn-cover').text('Select a Kingdom:');
}
});
$('#kingdom').change(function() {
$kingdom = $('#kingdom option:selected').val();
if ($kingdom == 'standard') {
$('#domain').removeAttr('disabled', 'disabled');
$('#phylum').attr('disabled', 'disabled');
$('.btn-cover').text('Select a Kingdom:');
} else {
$('#domain').attr('disabled', 'disabled');
$('#phylum').removeAttr('disabled', 'disabled');
$('.btn-cover').text('Select a Phylum:');
$.post("search.php", {
'domain': option
}, function(data) {
var sel = $("#kingdom");
sel.empty();
for (var i = 0; i < data.length; i++) {
sel.append('<option>' + data[i].name + '</option>');
}
}, "json");
}
});​
I'm having the most trouble understanding how the .post() function works. I know exactly what I want to do, just not exactly how to do.
My goal:
- obtain the value of the domain select box when it is changed
- use that value in the mysql query to get the relevant kingdoms
- execute the query using jquery and then populate the kingdom select box
Thanks!

Categories