I try to populate a select box based on the value of the another, by getting JSON data with jQuery from a PHP script that gets the data from a MySQL database.
This is my table :
I hope, if i select a different fruit from the first selection, it will change the available varieties in the second select.
According to my script, i'm not able to get corresponding available varieties into the second select, what wrong on my script.
<form>
Fruit:
<select name="name" id="fruitName">
<option>Apple</option>
<option>Banana</option>
<option>Orange</option>
<option>Pear</option>
</select>
Variety:
<select name="variety" id="fruitVariety">
</select>
</form>
<script>
function populate() {
$.getJSON('varities.php', {fruitName:$('#fruitName').val()}, function(data) {
var select = $('#fruitVariety');
var options = select.attr('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new Option(array['variety']);
});
});
}
$(document).ready(function() {
populate();
$('#fruitName').change(function() {
populate();
});
});
</script>
and this is my varities.php script
$result = array();
$fruitName = $_GET['fruitName'];
$res=mysql_query("SELECT variety FROM fruit WHERE name = '$fruitName' ORDER BY variety");
while ($row=mysql_fetch_array($res)){
array_push($result, array('variety'=>$row['variety']));
}
echo json_encode(array('result'=>$result));
Please any suggestions?
Try the following function
function populate() {
$.getJSON('varities.php', {fruitName:$('#fruitName').val()}, function(data) {
var select = $('#fruitVariety');
var options = select.empty();//empty the select box
$.each(data.result, function(index, array) {//don't forget you have a result array
select.append('<option value="'+array.variety+'">'+array.variety+'</option>');//append the option elements
});
});
}
Make 2 separate tables,one for the fruits and another for the variety. Id of tbl_fruits will be a foreign key in tbl_variety.
1)First get all fruits and store the results in $fruits.
Therefore, first select will be like:
<select name="name" id="fruitName">
<?php foreach($fruits as $fruit): ?>
<option value="<?=$fruit['id']?>"><?=$fruit['name']?></option>;
<?php endforeach; ?>
</select>
Then you can populate the 2nd dropdown using ajax:
<select name="variety" id="fruitVariety">
</select>
<script>
var id=$('#fruitName').val();
$.ajax({ // first call will get the list as per the initial value of the fruit list when the page loads
url:"get_variety.php",
method:"POST",
data:{initial:id},
dataType:"html",
success:function(data)
{
$('#fruitVariety').html(data);
}
});
$('#category').change(function(){
var id = $(this).val();
$.ajax({ // this will be triggered whenever you select a different value from the fruits list
url:"get-variety.php",
method:"POST",
data:{id:id},
dataType:"html",
success:function(data)
{
$('#fruitVariety').html(data);
}
});
</script>
And in get-variety.php:
Check if $_POST['initial'] or $_POST['id'] is set and fire query accordingly:
$initial=$_POST['initial'];
$results= After executing('SELECT * FROM tbl_variety WHERE fruit_id="'.$initial.'"');
foreach ($results as $result) {
echo '<option value="' . $result["id"] . '">'.$result["variety"].'</option>';
}
Similary, run the query for the other POST variable.
Related
I have two input field. I want to get value of 1st input field and sent it to database to get value of 2nd input field through php query. right now i am getting data in alert but I don't know how to put the values in second drop down.
I am getting data in alert. but how i can show data in #second-dropdown select tag.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#first-dropdown").off("change").on("change", function(){
$.ajax({
'url':"getUrl.php",
'data':{id:$("#first-dropdown").val()},
'method':'GET',
'success':function(data){
alert(data);
}
})
})
});
</script>
<select id="first-dropdown">
<option value="0">Select Product Line</option>
<option value="1">Living</option>
<option value="2">Kitchen</option>
<option value="3s">Bathe & Utility</option>
<option value="4">Furniture</option>
</select>
<select id="second-dropdown">
</select>
and my getUrl file is :
<?php
$id = $_GET['id'];
$query = mysql_query("select category_name from product_categories where Line_Code='$id'");
while($data = mysql_fetch_assoc($query)){
$values[] = array(
'product_categories'=>$data['category_name'],
);
}
echo json_encode($values);
?>
I want to show data in #second-dropdown. any one give me solution i am trying this since six hours.
this is for parsing your data in json
var new_data = $.parseJSON(data);
or add/edit your ajax property
datatype:"json"
Try this in your success function.
$("#second-dropdown").html('');
//var new_data = $.parseJSON(data);
$.each(new_data, function (i, item) {
$('#second-dropdown').append($('<option>', {
value: item.product_categories,
text : item.product_categories
}));
});
Here is one more way to do this (without json):
<?php
$id = $_GET['id'];
$query = mysql_query("select category_name from product_categories where Line_Code='$id'");
$retval="";
while($data = mysql_fetch_assoc($query)){
$retval=$retval."<option value='".$data['category_name']."'>".$data['category_name']."</option>";
}
echo $retval;
?>
and in your script:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#first-dropdown").off("change").on("change", function(){
$.ajax({
'url':"getUrl.php",
'data':{id:$("#first-dropdown").val()},
'method':'GET',
'success':function(data){
$("#second-dropdown").html(data);
}
})
})
});
</script>
$(document).ready(function(){
$("#first-dropdown").off("change").on("change", function(){
$.ajax({
'url':"getUrl.php",
'dataType':"json",
'data':{id:$("#first-dropdown").val()},
'method':'GET',
'success':function(data){
alert(data);
var results=data.d.results; //only assumption here this is a array of element with required option value. if it is not we need to print response data and check where all the value of options are stored.
var option='';
$("#second-dropdown").html('');
for(var i=0;i<results.length;i++)
{
option+='<option value="'+results[i]+'">'+results[i]+'</option>';
}
$("#second-dropdown").append(option);
}
})
})
});
Add this code in your success function to parse your JSON and create the options you want to add in your select element.
var options = JSON.parse(data);
for(var i in options){
$("#second-dropdown").append("<option value='"+ options[i].product_categories +"'>"+ options[i].product_categories +"</option>");
}
JSON.parse transform your JSON string as an array that you can manipulate with JavaScript.
The loop for create html options for the select then append these elements to the select.
HTML code is :
<select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<select name="freeitem" id="freeitem" class="form-control">
</select>
Js Code :
function getPrice(val) {
$.ajax({
type: 'post',
url: 'get_sales_price.php',
data: {
get_option: val
},
dataType: 'json',
success: function(response) {
console.log(response)
$('#freeitem').html(response.fritm);
}
});
}
and Php Code is :
$option = $_POST['get_option'];
$data = array();
$prdqty = $db->execute("select product_name from master_purchase where product_code='$option' and delet='0'");
while ($tqty = $prdqty->fetch_assoc())
{
$data['fritm'] = '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
}
echo json_encode($data);
while we selecting first selectbox content, need to add some data to second select box from database, we almost done the things but the second select box didn't show any values ,please help us to resolve the above problem
I tried your code with some hard code value and it perfectly working fine:-
Html+Jquery (in single page with .html extension):-
<select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<select name="freeitem" id="freeitem" class="form-control">
</select>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script><!-- added jquery library-->
<script type="text/javascript">
function getPrice(val) {
$.ajax({
type: 'post',
url: 'get_sales_price.php',
data: {
get_option: val
},
dataType: 'json',
success: function(response) {
console.log(response)
$('#freeitem').html(response.fritm);
}
});
}
</script>
Php (with hard-coded value):-
<?php
$option = $_POST['get_option'];
$data = array();
$data['fritm'] = ''; // you need to define it as empty string first
for($i = 0;$i<10;$i++) // hard-code started
{
$data['fritm'] .= '<option value="'.$i.'">'.$i.'</option>'; // append each option to the string one-by-one and check `.=` also
}
echo json_encode($data);
Output:-
http://prntscr.com/auyn7i
http://prntscr.com/auymzf
http://prntscr.com/auynij
Note:- problem may be occuring because either you missed jquery library of concatenation inside loop or some other error in your php file.
You need to do two things:
1) concatenate results in while loop. You are re-assigning the array variable causing latest one to overwrite the old one.
This way, only old value will be appended.
Change
$data['fritm'] = '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
To
$data['fritm'] .= '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
2) Change
$('#freeitem').html(response.fritm);
To
$('#freeitem').append(response.fritm);
As you are just appending options to drop down, not changing its HTML.
I've been trying and struggling all morning to get my combobox to update properly. Once a user selects and option in the first box I want to then populate a second box with options applicable to the first option chosen. I have written a separate php script to take in the option chosen and pull from the sql database the applicable return. This script works fine when run by itself but I cannot get it working within the javascript using AJAX
PHP:
<?php
$name=$_GET['name'];
// select box option tag
$selectBoxOption1 = '';
// connect mysql server
$con=mysql_connect('localhost', 'root', '');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mysql',$con);
$sql1 = "SELECT DISTINCT bike_type FROM bc_fit WHERE name='$name'";
$result1 = mysql_query($sql1);
// play with return result array
while($row = mysql_fetch_array($result1)){
$selectBoxOption1 .="<option value = '".$row['bike_type']."'>".$row['bike_type']."</option>";
}
// return options
echo $selectBoxOption1;
?>
Javascript (#nap2 is the current box and #nap 4 the next):
$("#nap2").change(function(event){
var selected = $(this).find('option:selected').text()
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
//need to get options based upon nap 2 choice by calling php script with selected and returning all unqiue bike under that name
var options4;
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: "name"=selected,
success: function(data) {
options4 = data;
}
});
$('#nap4').append($(options4));
});
You have a few issues in your jQuery:
<select id="nap2" class="napkeeComponent napkeeCombobox">
<option value="1">One</option>
<option value="2">Two</option>
<option value="2">Three</option>
</select>
<select id="nap4" class="napkeeComponent napkeeCombobox" disabled>
</select>
<script>
$(document).ready(function() {
$("#nap2").change(function(event){
// You just get the value of selected input
// You don't need to find anything because you've already selected it
var selected = $(this).val();
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$.ajax({
type: "GET",
url: 'getbiketype.php',
// Your creation of the data object is incorrect
data: { name: selected },
success: function(data) {
console.log(data);
// Here just append the straight data
$('#nap4').append(data);
}
});
});
});
</script>
I research in google and stack overflow for this answer there are lot of answer but i cannot able to get what i want.
I have two drop down menus and three text boxes.
PHP Code :
<select onchange="FirstDropDownClick()"> </select>
script code :
<script type="text/javascript">
function FirstDropDownClick() {
var selectDwn = document.getElementById("ID_dwn");
var selectedValue = selectDwn.options[selectBox.selectedIndex].value;
}
In "FirstDropDownClick()" i want the codes for the following :
1.select data from database according to the selected value.
2.Fill the text boxes with that.
3.Fill second drop down according to value of first drop-down menu.
I need an example codes. Because am stuck , dont know how to do .
Thanks in Advance.
your html code
<select name="reg_number" id="reg_number">
<option value="1">Reg1</option>
<option value="2">Reg2</option>
<option value="3">Reg3</option>
</select>
<input type="text" name="first_name" id="first_name">
your jquery(make sure you include jquery file)
$(document).ready(function(){
$('#reg_number').change(function(){
var reg_number = $(this).val();
var data_String;
data_String = 'reg_number='+reg_number;
$.post('ajax_file.php',data_String,function(data){
var data= jQuery.parseJSON(data);
$('#first_name').val(data.first_name)
});
});
});
your php code (ajax_file.php)
<?php
$reg_number =$_POST['reg_number'];
//run your query here to fetch the result and store it in a variable $data
echo json_encode($data);
exit();`
?>
If you want to do it with ajax and php
HTML
<select name="select_number" id="select_number">
<option value="1">Number1</option>
<option value="2">Number2</option>
<option value="3">Number3</option>
</select>
<input type="text" name="number_value" id="number_value">
JQuery
$(document).ready(function(){
$('#select_number').change(function(){
var number_value = $(this).val();
$.ajax({
method: 'POST',
url: "test.php",
data: {
'number_value' : number_value
},
dataType:'json',
success: callback = function(data, textStatus, xhr)
{
$('#number_value').val(data.number_value);
}
});
});
});
php (test.php)
<?php
echo json_encode($_POST);
?>
why you need php for that you can do it only with jquery or javascript
HTML
<select name="select_number" id="select_number">
<option value="1">Number1</option>
<option value="2">Number2</option>
<option value="3">Number3</option>
</select>
<input type="text" name="number_value" id="number_value">
Jquery
$(document).ready(function(){
$('#select_number').change(function(){
var number_value = $(this).val();
$('#number_value').val(number_value);
});
});
I'm working on a form. There are select elements and their options are from a database.
When i choose the first (for example a school class) the second have to show only those names who are in the class selected at first, from database too.
I'm rookie at Javascript and JQuery so I'm okay with page refreshing PHP solutions but I can't figure it out on my own. Can you please give me some instructions or advices how to start to work on this?
You can achieve this with ajax using preferably jquery and json.
javascript/ajax:
function fillSecondSelect()
{
$.get("ajaxFill.php?id=" + $("#class").val(),"",function(data) {
var selectData = "<option value=''> - Choose Student - </option>";
data = JSON.parse(data);
for(i=0;i<data.length;i++)
{
selectData += "<option value='" + data[i].id + "'>" + data[i].name + "</option>";
}
$("#students").html(selectData);
});
}
html:
<select id="class" name="class" onchange="fillSecondSelect()">
<option value=""> - Choose Class - </option>
<option value='1'>Class A</option>
<option value='2'>Class B</option>
</select>
<select id="students" name="students"></select>
ajaxFill.php (which should get the student data according the class id sent from mysql and serve it as JSON):
$result = mysqli_query($link,"SELECT * FROM students WHERE class_id = '" . $_GET['id'] . "'") or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($result))
{
$students[] = array("id" => $row['student_id'], "name" => $row['student_name']);
}
echo json_encode($students);
You use Jquery and Ajax to fetch the Students in a class based on the Class selected and load the student list into a Select element without refreshing the page.
HTML
<select id="selectedclass" onBlur="loadstudent();">
<option>class 1</option>
<option>class 2</option>
<option>class 1</option>
</select>
<select id="students" ></select>
Javascript
function loadstudent(){
var selectedclass = $('selectedclass').val();//user id
$.ajax({
type:'POST',
url: your php script,
data: 'selectedclass='+selectedclass,
dataType: 'json',
success: function(data)
{
var classlist='', html;
for(var i = 0; i < data.length; i++) {
classlist = data[i];
html+=classlist.students
}
//get number of outbox
$('#students').html(html);
},
error: function(jqXHR, exception) {
alert('Error');
}
});
}
PHP
<?php
include "config.php";//database connection file
//database using PDO
$db = pdoDB::getConnection();
//data from html
$student_class=$_POST['selectedclass'];
$query = "SELECT student_lastName,student_firstName
FROM student_table WHERE student_class='student_class'";
$result = $dbase->query($query) or die("failed!");
while ($row = $result->fetch(PDO::FETCH_BOTH)){
//credits info
$studentlist="<option>".$row['student_lastName']." ".$row['student_firstName']."</option>";
$results[] = array("students"=>$studentlist);
}
header('Content-type:application/json');
exit (json_encode($results));
?>
The data sent from the PHP script should be encoded with JSON
Modern websites use ajax to do this.
After the first item is selected an ajax request is sent which delivers the data for the second select.
There are many ways to build the second select. The ajax response could contain a json array with all the data and then you build the select field with js.
Or the response delivers complete html and all you have to do is to insert it.
I think this is exactly that you mean: http://codepen.io/man/pen/oBFlE
Put the js code in your file. You can have as many levels as you want. Explaining:
<select name="level1"><!--this is the "main" select-->
<option value="level2A">Level2A</option>
<option value="level2A">Level2B</option>
</select>
<select name="level2A"><!--this shows when the user selects the option with name ""level2A"-->
<option value="level3"></option>
</select>
<select name="level2B">
<!--options...-->
</select>
<select name="level3"></select>