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>
Related
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.
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.
Html file
The values for the sub combobox is retrieved by a php select query and the values are characters.
i have tried with integers values are perfectly passed.
<select name="sub" id="sub">
<option value="">Select semester first</option>
</select>
<select name="staff" id="staff">
<option value="">Select sub first</option>
</select>
Javascript
$('#sub').on('change',function(){
var SUB = $(this).val();
if(1){
$.ajax({
type:'POST',
url:'sta.php',
data:'sub='+SUB,//character is not passing.
success:function(html){
$('#staff').html(html);
}
});
}else{
$('#staff').html('<option value="">Select sub first</option>');
}
});
php file
if(isset($_POST["sub"]) && !empty($_POST["sub"]))
{
//Get all city data
$query = mysql_query("SELECT staff_name FROM subject WHERE course_name = ".$_POST['sub']);
//Count total number of rows
$rowCount = mysql_num_rows($query);//It always shows 0
//Display cities list
if($rowCount > 0){
echo '<option value="">Select staff</option>';
while($row = mysql_fetch_assoc($query)){
echo '<option value='.$row['staff_name'].'>'.$row['staff_name'].'</option>';
}
}else{
echo '<option value="">staff not available</option>';//when i tried to execute it comes here
}
}
There is simple syntactical error in your query in php just rewrite it as:
$query = mysql_query("SELECT staff_name FROM subject WHERE course_name = '".$_POST['sub']."'");
wherever you pass the data other than numbers always use single inverted comma such as'myData' to surround the values.
i am new to PHP and trying to arrive with similar functionality given in URL.
i have a form with four select options, result will be retrived when last option selected.
my current code is :
{
$result = mysql_query($query,$con);
if(!$result)
echo mysql_error();
$option = "";
while($row = mysql_fetch_assoc($result)) {
$option .= '<option value = "'.str_replace(' ', '_', $row['bankname']).'">'.$row['bankname'].'</option>';
}
str_replace(' ', '_', $row['bankname'])
?>
<form method = "POST" action = "">
<select name = "bank" onChange="document.location.href=bank[selectedIndex].value">
<?php echo $option; ?>
</select>
</form>
}
Probably i am asking very high level question, but please help.
Regards,
Anitha
You can send the first time using ajax, and whem the ajax is sucess you can change the submit the form again returning true.
If I got the question right, you are not looking for loading options into select box, but trying to look for a solution where the last select box have values:
<select id = 'finalSelect'>
<option value='http://aaaa.com'>A<option>
<option value='http://bbbb.com'>B<option>
<option value='http://cccc.com'>C<option>
</select>
and based on the user selection your page should redirect to aaaa.com, bbbb.com or cccc.com.
If I am right about your requirement, all you have to do is:
<select id = 'finalSelect' ONCHANGE="location = this.options[this.selectedIndex].value;>
<option value='http://aaaa.com'>A<option>
<option value='http://bbbb.com'>B<option>
<option value='http://cccc.com'>C<option>
</select>
I've been building a script for dynamic dropdowns using PHP and JQuery and I'm having an issue with some of the data being sent from the form to be queried. Basically the user will choose an option from the first box and from there ever other box is dependent on the previous. The options are pulled from a MySQL database and as these same options are being picked they are sent back to the script to create the next query and so on. I'm having issues with some of the data and I think it's because there are spaces in the options being sent through GET. I've looked over my script many times the past few days and I just can't find a solution.
Here is a live version of my script to test. - That's the url for a live version of the script to check out.
Here is the front-end. A pretty basic form and some javascript to send the information to the back-end script:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function(){
$("#series").change(function() {
$("#range").load("findbackend.php?series=" + $("#series").val());
});
$("#range").change(function() {
$("#digsize").load("findbackend.php?series=" + $("#series").val() + "&range=" + $("#range").val());
});
$("#digsize").change(function() {
$("#dignum").load("findbackend.php?series=" + $("#series").val() + "&range=" + $("#range").val() + "&digsize=" + $("#digsize").val());
});
});
</script>
</head>
<body>
<select id="series">
<option selected value="base">Please Select</option>
<option value="FM800">FM800</option>
<option value="F100">F100</option>
</select>
<br>
<select id="range">
<option>Please choose from above</option>
</select>
<br>
<select id="digsize">
<option>Please choose from above</option>
</select>
<br>
<select id="dignum">
<option>Please choose from above</option>
</select>
</body>
</html>
And here is the back-end I've come up up with:
<?php
//\\ MODULAR DEPENDANT DROPDOWNS \\//
//creates DB connection
$dbHost = 'host';
$dbUser = 'user';
$dbPass = 'pass';
$dbDatabase = 'database';
$con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error());
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
//prevents injections
$series = mysql_real_escape_string($_GET['series']);
isset($_GET['range'])?$range = mysql_real_escape_string($_GET['range']):"";
isset($_GET['digsize'])?$digsize = mysql_real_escape_string($_GET['digsize']):"";
isset($_GET['dignum'])?$dignum = mysql_real_escape_string($_GET['dignum']):"";
//forms the query depending on what data is recieved through GET
if (isset($_GET['dignum'])) {
$query = "SELECT DISTINCT * FROM meters WHERE series='$series' AND sio='$range' AND dig_size='$digsize' AND dig_num='$dignum' ORDER BY sio";
} elseif (isset($_GET['digsize'])) {
$query = "SELECT DISTINCT dig_num FROM meters WHERE series='$series' AND sio='$range' AND dig_size='$digsize' ORDER BY sio";
} elseif (isset($_GET['range'])) {
$query = "SELECT DISTINCT dig_size FROM meters WHERE series='$series' AND sio='$range' ORDER BY sio";
} else {
$query = "SELECT DISTINCT sio FROM meters WHERE series='$series' ORDER BY sio";
}
//creates a result array from query results
$result = mysql_query($query);
//outputs dropdown options dependent on what GET variables are set
if (isset($_GET['digsize'])) {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'dig_num'} . "'>" . $row{'dig_num'} . "</option>";
}
} elseif (isset($_GET['range'])) {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'dig_size'} . "'>" . $row{'dig_size'} . "</option>";
}
} else {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'sio'} . "'>" . $row{'sio'} . "</option>";
}
}
?>
Again, new.foxmeter.com/find.php is a live version of my script to check out.
This is a monospaced snippet of my table that I'm pulling data from: i.imgur.com/IOT9RUF.png
Thanks in advance for any help!
Your instincts were right, the problem is with non-escaped characters (url encoding). For debugging AJAX calls you should use your browser's console (I highly recommend FireBug, but to each his own).
Before you send the parameters via AJAX, you have to encode them using encodeURI(). For example:
$("#series").change(function() {
var val = document.getElementById('series').value;
// $("#series").val() == document.getElementById('series').value
// but the latter is faster!
$("#range").load(encodeURI("findbackend.php?series=" + val));
});
You would also have to adjust your other .change function calls accordingly. Since the data your PHP script will receive has been encoded, you need to decode it using urldecode(). Example:
$series = mysql_real_escape_string(urldecode($_GET['series']));
This should work just fine.
On a side note, you are using a deprecated MySQL API, you should use MySQLi or PDO. Also, your jQuery calls could do with some caching (you create the $("#series") object three separate times).
the easy way to use ajax so you need two php pages and one js at least
the first php will have the first dropdown and then send it`s value to the second php by ajax
it's simply example
first php code like this
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="dropdown.js"></script>
</head>
<body>
<select name="first" id="first">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<div id="second"></div>
</body>
</html>
dropdown2.php code is
<?php
if(isset($_GET['first'])){
$first=$_GET['first'];
echo"
<select name='second' id='secondselect'>
<option value='4'>$first a</option>
<option value='5'>$first b</option>
<option value='6'>$first c</option>
</select>
";
}
?>
and dropdown.js
$(document).ready(function(){
$("#first").change(function(){
str=$("#first").val();
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","dropdown2.php?first="+str,false);
xmlhttp.send();
document.getElementById("second").innerHTML=xmlhttp.responseText;
});
});