Hi i have 2 dropdown menu and i want populate my 2nd dropdown menu items with my 1st dropdown menu item related. I mean my 1st dropdown menu items are Apple, Samsung, HTC, Nokia etc. When i select Apple dropdown menu items populated by iPhone 6s, iPhone 5s, iPhone 4s etc. I can't explain it very well in english. Sorry my bad english. I populated my 1st dropdown menu from database
function selectFactor(){
$result = #mysql_query("SELECT * from Factors");
while($record = #mysql_fetch_array($result)){
echo '<option value="'.$record['FactorID'].'">'.$record['FactorName'].'</option>';
}
}
and display result in html file
<select name="dropdown" id="dropdown" onchange="bla()">
<?php selectFactor(); ?>
</select>
and i just try something with it bla bla bla...
function bla(){
var e = document.getElementById("dropdown");
var elementValue = e.options[e.selectedIndex].value;
console.log(elementValue);
}
how can i populate 2nd dropdown menu when 1st index is changed?
UPDATED!
<?php
$name = $_POST['selectedItem'];
function selectSum(){
$result = #mysql_query("SELECT * from factor INNER JOIN sumd ON factor.factorID=model.factorID where factorNer='$name'");
while($record = #mysql_fetch_array($result)){
echo '<option value="'.$record['factorID'].'">'.$record['modelNer'].'</option>';
}
}
?>
You need to query your database for the selected item:
get_data.php is the file you have to create where you will query your database.
You ont need this:
onchange="bla()
Just an ajax call:
$(document).ready(function(){
$('#dropdown').change(function(){
var selectedItem = $(this).val() //your item id
$.ajax({
url: 'get_data.php',
data : selectedItem,
dataType: "json",
type : 'POST',
})
.done(function(data) {
//put the returned data in the second selectbox
var output = '';
$.each(data, function(i, el){
output += '<option value="'+el.name+'">'+el.name+'</option>'
//where 'name' is at moment the placeholder of your returned data
})
$('#dropdown2').html(output)
})
.fail(function() {
console.log("error");
})
})
})
If you are ready with your query and don't know how to put the returned data into the second selectbox, I will also help you with it.
NOTE: this is your second select that has to be populated you need an unique ID in it:
<select name="dropdown2" id="dropdown2">
//here will be the output of the available options
</select>
One Important notice:
I advise you (when you have this working) to switch to mysqli and not use mysql anymore. This is a SECURITY ISSUE and you are potentially vulnerable for mysql injection!!
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.
So Ive been struggling with this problem all day and can't seem to get around it.
I need to call a php query whenever an option from a dropdown menu is selected.
<select class="selectpicker" id="headSelector">
<?php
$cname = $_GET['cname'];
$linkID = mysql_connect("localhost","USER","PASS");
mysql_select_db("USR", $linkID);
$SQLCurr = "SELECT `AName` FROM `Char-Armor` WHERE `CName` = '$cname' AND `AType`= 'Head'";
$currHeadValues = mysql_query($SQLCurr, $linkID);
$currRow = mysql_fetch_row($currHeadValues);
$curr = $currRow[0];
if($curr == '' || $curr == NULL){
$curr = 'None';
}
$SQLHead = "SELECT AName FROM `Armor` WHERE AType = 'Head'";
$allHeadValues = mysql_query($SQLHead, $linkID);
echo "<option>".$curr."</option>";
while($row = mysql_fetch_assoc($allHeadValues)){
echo "
<option>".$row['AName']."</option>
";
}
?>
</select>
The php part needs to take the 'AName' from the option and use it to insert into a table.
I have done a lot of reading about AJAX but I do not quite understand how it is supposed to work. I think it is like html -> js -> Ajax -> php
I need it to stay on the same page when an option is selected.
Any explanation would be great, thanks!
Here's what you can do.
1). As soon as an option is selected, run a jquery onchange event and get the value of the selected option.
2). Now, run an ajax request with the value of the selected value and post this data to a backend php file.
3). Now on this backend php file, receive data and process (run the query).
Code Sample.
Change your option line in this way.
<option value="$row['AName']">".$row['AName']."</option>
jQuery-Ajax
$("#headSelector").change(function(e){
//get the value of the selected index.
value = $(this).val();
//make an ajax request now
$.ajax({
url: 'yourPhpBackendScript.php',
type: 'POST',
data: {value: value},
success:function(response)
{
alert(response);
}
})
})
yourPhpBackendScript.php
//You can now receive the selected value as $_POST['value'];
//get the value now
$value = $_POST['value'];
//you can apply validations if you want.
//Now, run the query and send a response. Response can be a simple message like data submitted etc. So
runQueryHere
echo "inserted"; //response returned to ajax rquest
First of all, return the string like this:
$options_arr = '';
while($row = mysql_fetch_assoc($allHeadValues)){
$options_arr .= "<option>".$row['AName']."</option>
";
}
echo $options_arr;
Use the change event like this:
$("#headSelector").change(function(){
$.ajax({
data: '',
url: 'your_url',
type: 'POST',//Or get
success: function(options_array){
$("#headSelector").empty().append(options_str);
}
});
});
i already search for this question but the result is a litte confusing because today is my first time to encounter ajax and most answer is ajax. so i decided to post a question which is my work and trying to have someones help from here to guide me about ajax. this is for my project need some help please
this is my query for getting the values from database and display it to my dropdownlist
<?php
include('config.php');
$sql="SELECT food FROM menu";
$lists=mysql_query($sql);
?>
this is my dropdown list... i fetch data from my database to have my values in dropdown list
<select name="fname" id='mySelect' value='Foodname'>
<?php
while($food = mysql_fetch_array($lists)) {
echo '<option value='.$food['food'].'>'.$food['food'].'</option>';
}
echo '</select>';
?>
now i want to show the price of the selected food in the dropdown list.. i want it to show in input text so i am able to edit it if i want to
<input type='text' class="form-control" name='prc'>
this is my database
for select options give value as the database Id, like this
echo '<option value='.$food['id'].'>'.$food['food'].'</option>';
considering as id to be autoincrement column in DB.
Then write ajax like this.
$(document).ready(function() {
$("#mySelect").change(function(){
var val = $('#mySelect option:selected').val();
$.ajax({
url: "path to php file to get the price",
type: "POST",
dataType: "HTML",
data: {"id": val}
async: false,
success: function(data) {
// for textbox add id as price
$("#price").val(data);// data will have the price echoed in somefilename.php
}
});
});
});
Lets say the url in ajax is somefilename.php
so in somefilename.php, yyou shud write query like this
<?php
include('config.php');
$id = $_POST['id'];//same name as in ajax data
$sql="SELECT price FROM menu where id = $id";
// echo the price here
?>
What ever you echo here, it will come in ajax success function with parameter 'data', then you can assign to the required textbox as i have done in success function()
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 have a form that has a dropdown selection menu that loads invoice ids from my database. I'm trying to prefill my form based on the value of the invoice selected from the drop down menu. In my database is a column "invoiceidcopy" which contains a value(s) that shows as a selection(s) for my drop down menu. If you notice in my image of my database table below you will notice the first row/record's invoiceidcopy field is blank..in my drop down menu ...of course...the first selection is blank. Ultimately my code below im trying to get to prefill my form works only when i select the blank selection from the drop down menu but not for the other 2 selections? How can I prefill my form based on a dropdown menu selection value?
FORM
<form action="#">
<select id="dropdown-select" name="dropdown-select">
<option value="">-- Select One --</option>
</select>
<button id="submit-id">Prefill Form</button>
<input id="txt1" name="txt1" type="text">
<input id="txt2" name="txt2" type="text">
<button id="submit-form" name="Submit-form" type="submit">Submit</button>
</form>
SCRIPT
<script>
$(function(){
$('#submit-id').on('click', function(e){
var invoiceidcopy = $('#dropdown-select').val();
e.preventDefault();
$.ajax({
url: "/tst/orders2.php",
data: {
invoiceidcopy: invoiceidcopy
}
}).done(function(data) {
data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
});
});
});
</script>
/tst/orders2.php
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
// Check if the connection failed
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
if (isset($_GET['invoiceidcopy']))
{
$invoiceidcopy= $_GET['invoiceidcopy'];
$query = "SELECT txt1, txt2, q1
FROM seguin_orders
WHERE invoiceidcopy = '".($invoiceidcopy)."'";
$result = mysqli_query($con,$query);
while ($row = mysqli_fetch_assoc($result))
{
echo json_encode($row);
die();
}
}
?>
it seems the source of your error is from the json data you are sending to php via ajax. you should try enclosing the data key in quotes so that javascript will not replace it with the variable value.
data: {
'invoiceidcopy': invoiceidcopy
}
Another possible source of your error is the sql to select the records from the table.
Have you tried removing the brackets from the variable name like so
$query = "SELECT txt1, txt2, q1
FROM seguin_orders
WHERE invoiceidcopy = '".$invoiceidcopy."'";
or even using braces like
$query = "SELECT txt1, txt2, q1
FROM seguin_orders
WHERE invoiceidcopy = {$invoiceidcopy}";
Also it will be good to check the value before it is sent to php just to be sure it is what you expect. For example you can do something like:
e.preventDefault();
var invoiceidcopy = $('#dropdown-select').val();
alert(invoiceidcopy); /*display the value to confirm it is correct */
// use the javascript console
console.log(invoiceidcopy);