Optgroup issue in jquery - php

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);
}
});
})
});

Related

Ajax select option group not working

Categories and services are stored into two tables (category, service). I need to load all categories and services to a single select box based on staff selection.
//Jquery
$('.staff').change(function() {
var services = $('.service').empty();
$('<option value="" disabled selected hidden>--Select Service--</option>').appendTo(services);
$.get('ajax_service.php', {tutor: $(this).val()}, function(result) {
$.each(JSON.parse(result), function(index, item) {
$('<optgroup label="' + index + '">').appendTo(services);
$.each(item, function (name, value) {
$('<option value="' + name + '">' + value + '</option>').appendTo(services);
});
$('</optgroup>').appendTo(services);
});
});
});
//ajax_service.php
if(isset($_GET['staff'])) {
$staff_id = $_GET['staff'];
$sql = "SELECT c.category_id, c.category_name, s.service_id, s.service_name "
. "FROM service s "
. "INNER JOIN category c ON s.category_id = c.category_id "
. "WHERE s.staff_id = ? "
. "ORDER BY s.sort_order ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($staff_id));
$services = $stmt->fetchAll();
$groups = array();
foreach ($services as $service) {
$groups[$service['category_name']][$service['service_id']] = $service['service_name'];
}
echo json_encode($groups);
}
This code loads all categories and services but the option group is not works as expected
Result HTML Code
<select class="service" name="ddlService" id="ddlService">
<option value="" disabled="" selected="" hidden="">--Select Service--</option>
<optgroup label="Advertising"></optgroup>
<option value="1">Adware</option>
<option value="2">Brands</option>
<option value="3">Modeling</option>
<option value="4">Sponsorships</option>
<option value="5">Press Release</option>
</select>
What's wrong with this code?. Can anyone help me track the issue? Thank you very much for your time.
//Jquery
$('.staff').change(function() {
var services = $('.service');
var html='';
$('<option value="" disabled selected hidden>--Select Service--</option>').appendTo(services);
$.get('ajax_service.php', {tutor: $(this).val()}, function(result) {
$.each(JSON.parse(result), function(index, item) {
html+='<optgroup label="' + index + '">';
$.each(item, function (name, value) {
html+= '<option value="' + name + '">' + value +'</option>');
});
html+= '</optgroup>');
});
});
services.append(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.

How to call/activate the 2nd select list only after 1st select list was selected?

I have the following select list:
SELECT LIST 1:
<select name="productcolor" id="productcolor" onChange="GetAvailProductSizes();">
<option value=""><? echo $langdata['oneprodpage_selectcolor']; ?>...</option>
<? foreach ($thisproduct['availcolors'] as $color) { ?>
<option value="<? echo $color['id']; ?>"><? echo $color['name']; ?></option>
<? }; ?>
</select>
SELECT LIST 2:
<select name="productsize" id="productsize" style="width: 120px;">
<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>
</select>
If in LIST 1 no options where selected, LIST 2 will be empty. It's like LIST 2 depends of LIST 1.
This is made with this function:
<script type="text/javascript"><!--
function GetAvailProductSizes() {
$('select#productsize option').remove();
$('select#productsize').append('<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>');
var color = $('#productcolor').val();
if (color > 0) {
var availsizes;
var http_request = new XMLHttpRequest();
http_request.open( "GET", '<? echo ROOT; ?>/autocompleteavailsizes/?productid=<? echo $thisproduct['id']; ?>&color=' + color, true );
http_request.send(null);
http_request.onreadystatechange = function () {
if ( http_request.readyState == 4 ) {
if ( http_request.status == 200 ) {
availsizes = eval( "(" + http_request.responseText + ")" );
for (var i = 0; i < availsizes.length; i++) {
$('select#productsize').append('<option value="' + availsizes[i].id + '">' + availsizes[i].name + '</option>');
};
} else {
alert( "There was a problem with the URL." );
}
http_request = null;
}
};
};
}
//-->
</script>
Now, I want the SELECT LIST 2 to be hidden until SELECT LIST 1 was not touched. Any help please with PHP or jQuery. Thank you!
Simply add display:none to the style attribute of the second list and use $('select#productsize').show(); inside your function to let it appear,

not displaying selected options in drop down menu

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

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