Dropdown Options Based on Previous Selection - php

I'm hoping this is a simple solution. I am trying to make the first drop down determine the options available for the second. In my database, each flavor for the drink type has "type_id" column set as an integer (i.e. 1,2,3). The integers are meant to reflect the category in which they belong. Is it possible/make sense to base the available options for the second drop down off of the "type_id" that I determined?
I was hoping to accomplish this by using PHP, but I am not opposed to jQuery. I am not very well versed in one over the other. Thank you for your help in advance!
<?php
require "db-connect.php";
$dtype = "SELECT name FROM drinktype";
$typedata = mysqli_query($connection, $dtype);
echo "<select id='slctType'>";
if (mysqli_num_rows($typedata) > 0) {
while($row = mysqli_fetch_assoc($typedata)) {
echo "<option value='{".$row['name']."}'>".$row['name']."</option>";
}
}
echo "</select>";
$dflavor = "SELECT type_id,name FROM drinkflavor";
$flavordata = mysqli_query($connection, $dflavor);
echo "<select id='slctFlavor' ";
if (mysqli_num_rows($flavordata) > 0) {
while($row = mysqli_fetch_assoc($flavordata)) {
echo "<option value='{".$row['name']."}'>".$row['name']."</option>";
}
}
echo "</select>";
mysqli_close($connection);
?>

I have sample code for fetching the city according to their state. I have do that code with ajax, jquery and php. I think you have similar type of requirement. Please try below code concept for your requirement.
$(document).on('change','#state',function () {
$('#city').remove();
if($(this).val() != 'none')
{
var state_id = $(this).val();
$.ajax({
type: 'POST',
url: 'page.php',
data: { state_id: state_id },
success: function (city_response) {
if(city_response == '')
{
return false;
}
else
{
var city = '<select name="city" id="city" class="form-control">';
city += '<option value="-----">Please select any City</option>';
$.each(city_response, function (ck, cv) {
city += '<option value="' + cv['city_id'] + '">' + cv['city_name'] + '</option>';
});
city += '</select>';
$("#city_div").css('display', 'block');
$('#cities').append(city);
}
}
})
}
else
{
$("#city_div").css('display', 'none');
}
});

Related

I have three selects on my form. Each depends on the values of the previous one

I have three selects on my form.
Each depends on the values of the previous one.
I mean there is drop-down list with categories, car brand and car model.
The list with car brand must show the brands of chosen category. Also car model have consist of models of chosen brand.
The form HTML, the server language is PHP, I want to use Ajax JQUERY to get the value of the select.
Help please how it should be?
You should do something like this:
jQuery(function($) {
var brands = {
'Trucks': ['Ford', 'Chevrolet'],
'Cars': ['Honda', 'Volkzwagen'],
}
var models = {
'Ford': ['Model1', 'Model2'],
'Chevrolet': ['Model3', 'Model4'],
'Honda': ['Model5', 'Model6'],
'Volkzwagen': ['Model7', 'Model8'],
}
var $brands = $('#brand');
var $models = $('#model');
$('#category').change(function () {
var category = $(this).val(), brnds = brands[category] || [];
var html = $.map(brnds, function(brnd){
return '<option value="' + brnd + '">' + brnd + '</option>'
}).join('');
$brands.html('<option>Select</option>'+html)
$models.html('');
});
$('#brand').change(function () {
var brand = $(this).val(), mdls = models[brand] || [];
var html = $.map(mdls, function(mdl){
return '<option value="' + mdl + '">' + mdl + '</option>'
}).join('');
$models.html(html)
});
});
Check this JSFiddle: http://jsfiddle.net/minijavi19/2pza5/1908/
Of course if you want to use Ajax you should set your variables with it.
Thanks to everybody who paid attention to my question!!! But I want share with you with my solution. There ara 3 files: index.php, ajax-queries.js, php-funcs.php.
//index.php
$categories = $mysqli->query("SELECT category_id, category_name FROM
categories") or die($mysqli->error);
<form action="../../php/admin_funcs.php" method="post">
<select id="cat_slc" class="lists" name="category" >
<option disabled selected>Выберите категорию</option>
<?php
while ($crow = $categories->fetch_assoc())
{
echo "<option
value='".$crow['category_id']."'>".$crow['category_name']."
</option>";
}
?>
</select>
<select id="marka_slc" class="lists marka-select" name="marka" >
<option disabled selected>Выберите марку</option>
</select>
<select id="model_slc" class="lists model-select" name="mode">
<option disabled selected>Выберите модель</option>
</select>
</form>
//ajax-queries.js
$('#cat_slc').change(function () {
var cat_id = $(this).val();
var url = '../../php/data_functions.php';
$('#marka_slc').load(url + '#mark-block', {cat_id: cat_id}, function () {
$('.marka-select').fadeIn('slow');
});
});
$('#marka_slc').change(function(){
var mark_id = $(this).val();
var url = '../../php/data_functions.php';
$('#model_slc').load(url + '#model-block', {mark_id: mark_id}, function (){
$('.model-select').fadeIn('slow');
});
});
//php-funcs.php
<?php
require_once "db_connect.php";
function GetMarkas(){
global $mysqli;
$category_id = $_POST['cat_id'];
$query = "SELECT marka_id, marka_name FROM marka WHERE category_id =
'".$category_id."'";
$result = $mysqli->query($query);
$data = '';
while ($row = $result->fetch_assoc()){
$data .= "<option value='".$row['marka_id']."'>".$row['marka_name']."
</option>";
}
return $data;
}
function GetModels(){
global $mysqli;
$mark_id = $_POST['mark_id'];
$query = "SELECT model_id, model_name FROM model WHERE marka_id=
'".$mark_id."'";
$result = $mysqli->query($query);
$data = '';
while ($row = $result->fetch_assoc()){
$data .= "<option value='".$row['model_id']."'>".$row['model_name']."
</option>";
}
return $data;
}
if(isset($_POST['mark_id'])){
echo"<div id='model-block'>" . GetModels() . "</div>";
}
else if(isset($_POST['cat_id'])){
echo"<div id='mark-block'>" . GetMarkas() . "</div>";
}

How to call the value of select box from different file?

I created 2 files:
1. post.php
2. ajax.php
i want to select 2 select box to show the related chart. the select box is coded in post.php. The data query is in the ajax.php file. i want to code the select box logic in ajax.php so that the chosen select box data will be sent to post.php using ajax call.
but, I don't know how to call the variable selected value of select boxes in ajax.php to run the function there.
Anyone can help me?
this is the code from post.php
//combo box options to select post filter
echo 'Posts of : ';
echo '<select id="post-filter">';
echo '<option value="0" selected="selected"> Select </option>';
echo '<option value="1">Job</option>';
echo '<option value="2">Internship</option>';
echo '</select>';
echo ' ';
//combo box options to select group filter
echo 'Category : ';
echo '<select id="field-filter">';
echo '<option value="0" selected="selected"> Select </option>';
echo '<option value="1">Company</option>';
echo '<option value="2">Location</option>';
echo '<option value="3">Jobs Category</option>';
echo '<option value="4">Salary</option>';
echo '<option value="5">Experience</option>';
echo '<option value="6">Level of Education</option>';
echo '</select>';
?>
function change1() {
var listbox1 = document.getElementById("post-filter");
var selIndex1 = listbox.selectedIndex;
var selValue1 = listbox.options[selIndex1].value;
var selText1 = listbox.options[selIndex1].text;
}
function change2() {
var listbox2 = document.getElementById("post-filter");
var selIndex2 = listbox.selectedIndex;
var selValue2 = listbox.options[selIndex2].value;
var selText2 = listbox.options[selIndex2].text;
}
this is the ajax.php file to get the chosen data value
if (selValue1 == '1') {
if (selValue2 == '1') {
x = CompanyData;
y = optionsCompany;
}
if (selValue2 == '2') {
x = LocationData;
y = optionsLocation;
}
if (selValue2 == '3') {
x = CategoryData;
y = optionsCategory;
}
if (selValue2 == '4') {
x = SalaryData;
y = optionsSalary;
}
if (selValue2 == '5') {
x = ExperienceData;
y = optionsExperience;
}
if (selValue2 == '6') {
x = LevelData;
y = optionsLevel;
}
}
elseif (selValue1 == '2') {
if (selValue2 == '1') {
x = CompanyData;
y = optionsCompany;
}
if (selValue2 == '2') {
x = LocationData;
y = optionsLocation;
}
if (selValue2 == '3') {
x = CategoryData;
y = optionsCategory;
}
if (selValue2 == '4') {
x = SalaryData;
y = optionsSalary;
}
if (selValue2 == '5') {
x = ExperienceData;
y = optionsExperience;
}
if (selValue2 == '6') {
x = LevelData;
y = optionsLevel;
}
}
can i use this?
$(document).ready(function() {
$('select[name="post-filter"]').change(function(){
var select1 = $(this).val();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {select1: select1},
dataType: 'php'
});
});
});
Post.php
<?php
//combo box options to select post filter
echo 'Posts of : ';
echo '<select id="post-filter">';
echo '<option value="0" selected="selected"> Select </option>';
echo '<option value="1">Job</option>';
echo '<option value="2">Internship</option>';
echo '</select>';
echo ' ';
//combo box options to select group filter
echo 'Category : ';
echo '<select id="field-filter">';
echo '<option value="0" selected="selected"> Select </option>';
echo '<option value="1">Company</option>';
echo '<option value="2">Location</option>';
echo '<option value="3">Jobs Category</option>';
echo '<option value="4">Salary</option>';
echo '<option value="5">Experience</option>';
echo '<option value="6">Level of Education</option>';
echo '</select>';
?>
<script>
$(document).ready(function() {
// for post-filter
$('#post-filter').on('change',function(){
var select1 = $(this).val(); // Post filter value
var select2 = $("#field-filter").val(); // Field Filter value
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {selValue1 : select1,selValue2 :select2 },
success: function(result){
console.log(result); // what ever the ajax call response we got from ajax.php
}
});
});
// we need to do the same for field filter value.
$('#filed-filter').on('change',function(){
var select2 = $(this).val(); // Field filter value
var select1 = $("#post-filter").val(); // post Filter value
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {selValue1 : select1,selValue2 :select2 },
success: function(result){
console.log(result); // what ever the ajax call response we got from ajax.php
}
});
});
</script>
ajax.php will be the same as you have done.

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.

Does not save html select data from ajax query to session

I'm creating a form where the users have to select their country and city from a select field, which is dynamically updated corresponding to the actual country selected. However when the form is submitted everything is getting saved successfully except the city.
I'm using jquery select2 and jquery validation plugin, I think those could cause the problem.
Here is the main code:
$('#country').select2().change(function() {
$("#city").select2('data', null);
$.ajax({
type: 'post',
url: 'search_city.php',
data: 'country=' + $(this).val(),
dataType: 'html',
success: function(response) {
$('#city').html(response);
}
});
});
and
<label>* City:</label>
<select id="city" name="property_city" required>
<option></option>
</select>
and this is search_city.php
echo '<option></option>';
while($city = mysqli_fetch_object($cities)) {
if($_SESSION['property_city'] == $city->id) {
echo '<option selected value="'.$city->id.'">'.$city->name.'</option>';
} else {
echo '<option value="'.$city->id.'">'.$city->name.'</option>';
}
}
When the form is submitted a validation php runs where I save the data to session variables. There are more inputs, not just the country and the city, and they are saved successfully except the city I mentioned.
I can't figure out what the problem is. I did't include all the code, maybe something else could cause the problem, however if someone could find it here I would be relieved.
You need to write,
$html = '<option value=""></option>';
while($city = mysqli_fetch_object($cities)) {
if($_SESSION['property_city'] == $city->id) {
$html .= '<option selected value="'.$city->id.'">'.$city->name.'</option>';
} else {
$html .= '<option value="'.$city->id.'">'.$city->name.'</option>';
}
}
echo $html;

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