Append json data to HTML List box - javascript

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.

Related

Load MySQL data without Refresh Webpage

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.

Multiple dynamic drop down select menus not working - PHP MySQL Jquery

I am building a form that will have three related drop down menus. First one is store locations, second Equipment at this location, third is components at this location.
So when I pick a location the page sends an AJAX request to load the select values for the equipment at this location. And when I pick the equipment it should load the components that belong to that equipment.
The third drop down for components is what's not appearing.
So my first drop down goes like this off the main file with the divs where the drop downs are added via AJAX calls:
<div class="input-group">
<strong>Select A Store Location:</strong>
<select class="form-control selectDesk" name="Location_ID" id="Location_ID">
<option value=1>HT1</option>
<option value=2>HT2</option>
<option value=3>HT3</option>
<option value=4>HT4</option>
<option value=5>HT5</option>
<option value=6>HT6</option>
</select>
</div>
<div id="equipment">
</div>
<div id="component">
</div>
The second drop down is dynamic loaded off a different file and inserted in a div via Jquery and AJAX. This is the code to make that happen
<?php
include('DBConnect.php');
$locID = $_POST['loc_id'];
$equipSQL ="SELECT Equipment_ID, Equipment_Name FROM Equipment WHERE Location_ID = $locID";
$equipResult = $my_dbhandle->query($equipSQL);
$numResults = $equipResult->num_rows;
?>
<strong>Select Equipment:</strong>
<div class="input-group">
<select class="form-control" name="Equipment_ID" id="Equipment_ID" style="min-width: 375px;">
<option value="0">No Equipment Needed For This Task</option>
<?php
for ($i=0; $i < $numResults; $i++){ //this will loop through the results and print them in the drop down menu
$row = $equipResult->fetch_assoc(); //Parse result into rows
echo "<option value=" . $row['Equipment_ID'] . ">" . $row['Equipment_Name'] . "</option>\n";
}
?>
</select>
</div>
And my third drop down is also loaded off another file via Jquery and AJAX
<?php
include('DBConnect.php');
$equipID = $_POST['equip_id'];
$compSQL ="SELECT Component_ID, Component_Name FROM Components WHERE Equipment_ID = $equipID";
$compResult = $my_dbhandle->query($compSQL);
$numResults = $compResult->num_rows;
?>
<strong>Select Component:</strong>
<div class="input-group">
<select class="form-control" name="Component_ID" id="Component_ID" style="min-width: 375px;">
<option value="0">No Component Needed For This Task</option>
<?php
for ($i=0; $i < $numResults; $i++){ //this will loop through the results and print them in the drop down menu
$row = $compResult->fetch_assoc(); //Parse result into rows
echo "<option value=" . $row['Component_ID'] . ">" . $row['Component_Name'] . "</option>\n";
}
?>
</select>
</div>
The Jquery is as follows:
<script>
$("#Location_ID").change(function(){
var locID = "";
var locID = $('#Location_ID').val();
$.ajax({
type: 'post',
url: 'equipDropDownByLocRepeatingTask.php',
data: 'loc_id=' + locID,
success: function (r) {
$('#equipment').html(r);
}
});
}).change();
$("#Equipment_ID").change(function(){
var equipID = "";
var equipID = $('#Equipment_ID').val();
$.ajax({
type: 'post',
url: 'compDropDownByLocRepeatingTask.php',
data: 'equip_id=' + equipID,
success: function (r) {
$('#component').html(r);
}
});
}).change();
</script>
So again, the first AJAX request for the second equipment drop down is loaded just fine. But the third drop down for the component select is not.
Thank you in advance for your help!
Hi I have modified your code please use this.
If this will work then I will explain the script
<script>
$("#Location_ID").change(function(){
var locID = "";
var locID = $('#Location_ID').val();
$.ajax({
type: 'post',
url: 'equipDropDownByLocRepeatingTask.php',
data: 'loc_id=' + locID,
success: function (r) {
$('#equipment').html(r);
initSecond();
}
});
}).change();
function initSecond(){
$("#Equipment_ID").change(function(){
var equipID = "";
var equipID = $('#Equipment_ID').val();
$.ajax({
type: 'post',
url: 'compDropDownByLocRepeatingTask.php',
data: 'equip_id=' + equipID,
success: function (r) {
$('#component').html(r);
}
});
}).change();
}
</script>
Try to execute this javascript :
$("#Equipment_ID").change(function(){ ....
... after the first ajax call, like this:
success: function (r) {
$('#equipment').html(r);
$("#Equipment_ID").change(function(){
...
...
}
}
Also the third dropdown should be:
<select name="Component_ID" and id="Component_ID" ...

Using AJAX and PHP to change combobox choices

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>

populate text boxes depend on drop-down selection in php

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

How to make <select> <option> related to another <select>'s <option>?

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>

Categories