Using AJAX and PHP to change combobox choices - javascript

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>

Related

How to add a <select> <option> with jquery dynamically?

Changed value of <select> on success response from API with:
jQuery('#vat').val(response);
With this returned value can be placed into a textbox, but need to change the selected value of a combobox.
How to realize this?
Here is jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getVat() { // Do an Ajax request to retrieve the product price
console.log("getVat before ajax", jQuery('#product_name').val());
jQuery.ajax({
url: './get/vat/get1.php',
method: 'POST',
data: {'id' : jQuery('#product_name').val()},
success: function(response){
console.log("getPrice after ajax", jQuery('#product_name').val());
jQuery('#vat').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
The script works when #vat is a textbox but not when #vat is a combobox.
Update:
Here is the script been using for the combobox:
<?php
$dbname = 'db';
$dbuser = 'root';
$dbpass = 'pass';
$db = new mysqli('localhost', $dbuser, $dbpass, $dbname);
if (!$db) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
?>
<select style="width:100%" id="vat" name="vat">
<option value = "0">No VAT</option>
<?php
$queryusers = "SELECT id, internal_id, name FROM vat";
$db = mysqli_query($db, $queryusers);
while ( $d=mysqli_fetch_assoc($db)) {
echo "<option value='".$d['id']."'>".$d['internal_id']." | ".$d['name']."</option>";
}
?>
</select>
Update 2:
The selected value is changed to '1'. But the script still shows <option value = "0">No VAT</option>. Does someone know how I can update the data that is shown.
Update 3:
I just get a extra option when I run the following script. The value that is represented as the selected value is still the same:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getVat() { // Do an Ajax request to retrieve the product price
console.log("getVat before ajax", jQuery('#product_name').val());
jQuery.ajax({
url: './get/vat/get1.php',
method: 'POST',
data: {'id' : jQuery('#product_name').val()},
success: function(response){
// and put the price in text field
var newOption = "<option value=" + response + ">" + response + "</option>";
$("#vat").append(newOption);
$("#vat").val(response);
getPrice();
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
You are right <select> value will be changed with $("#vat").val(1). However this will not create a new <option>. If there would be an <option value="1"> then this option would have been shown. Since it doesn't exist thus HTML have nothing to show and showing default <option> of <select>.
You need to create a <option> and append it to <select>.
Here's jQuery on success:
var newOption = `<option value=` + response + `>` + response + `</option>`;
$("#vat").append(newOption);
$("#vat").val(response);

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.

Append json data to HTML List box

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.

Adaptive Drop Down Menu with PHP functions Populating from a MySQL server

I have three drop down menus that I have been trying to make dependent on one another so that once a selection has been made in the first drop down, the options for the second one will change. Then once a selection has been made in the second drop down menu, the third dropdown menu will change. My HTML looks like this:
<select class = "homepageSelectors , hpSelectorMenu" id = "classSelector" name="classSelector" >
<option selected="selected">Select</option>
<option value= "geometry">Geometry</option>
<option value= "english1">English 1</option>
<option value= "algebra2">Algebra 2</option>
</select>
<select class = "homepageSelectors , hpSelectorMenu" id = "levelSelector" name="levelSelector">
</select>
<select class = "homepageSelectors , hpSelectorMenu" id = "teacherSelector" name="teacherSelector">
</select>
The first drop down is hard coded because the options will not change. Although, what I need to do is when the first one is changed, run a PHP function to query an SQL database and get the options for the second dropdown menu. I have the following jquery code in another file that runs a function when the first dropdown is changed.
$("#classSelector").change( function () {
//In here is where I need to run a PHP function
});
I realize that I can call an external PHP file from in that jquery function, although my problem is that once I query my SQL server from that external PHP file, I have no way of returning the results from the query to my HTML file so that the second drop down menu can be populated.
I have been looking at other forums trying to find a solution, although I was unable to find any posts similar to my scenario. I am not too familiar with ajax, but if you think that it is the way to do it, please do explain. THANKS FOR ALL THE HELP!!!
You need to use jQuery Ajax
Make a request the .php file in order to get the data you want. A way simple example to get you an idea:
Your javascript function file:
$("#classSelector").change( function () {
//In here is where I need to run a PHP function
var value = $(this).val();
// load data if value is different than 'selected'
if(value != 'selected') {
$.ajax({
url: 'your_file.php',
data: {classID: $(this).val()},
dataType: 'html',
type: "GET",
success: function(data) {
// drop the output in #levelSelector select
$('select#levelSelector').html(data);
}
});
}
});
This can be translate to something like your_file.php?classID=Geometry for example:
Your php file:
<?php
// This is an example your php script should output what you need
// and how you need even if loading data from SQL Server / MySQL etc...
$classID = (isset($_GET['classID'])) ? $_GET['classID'] : null;
switch($classID)
{
case 'Geometry':
echo "<option value='level1'>Level 1</option>";
break;
default:
break;
}
// Output
<option value='level1'>Level 1</option>
The output will be inside the '#levelSelector' select and like this:
<select class = "homepageSelectors , hpSelectorMenu" id = "levelSelector" name="levelSelector">
<option value='level1'>Level 1</option>
</select>
So, I think what you're really asking for here is: how do I use JavaScript and PHP to live-query a database?
There are two parts to this. The JavaScript script and the PHP script. JavaScript will make an AJAX call to the PHP script, which will then query the database and return the results of that query to the JavaScript that made the initial request.
It seems you are already using jQuery, so that's great, since jQuery has a really useful feature for making network calls: $.ajax()
Taking the code you already have and expanding it:
$("#classSelector").change( function () {
var selectedClass = $(this).find(":selected").text();
$.ajax({
url: '/path/to/class/select/php/script.php',
data: {selectedValue: selectedClass}, // Send this data to the PHP script
dataType: 'json', // Let's assume the PHP script will send us a JSON response
success: function(data) { // Gets called if the entire request is successful
console.log('Server returned level options for class ' + selectedClass, data);
// data now contains the array of options for levelSelector.
// I'm going to assume you know how to loop through them and populate levelSelector
}
});
});
We need the exact same code for levelSelector, just changing two little things:
$("#levelSelector").change( function () {
var selectedLevel = $(this).find(":selected").text();
$.ajax({
url: '/path/to/level/select/php/script.php',
data: {selectedValue: selectedLevel}, // Send this data to the PHP script
dataType: 'json', // Let's assume the PHP script will send us a JSON response
success: function(data) { // Gets called if the entire request is successful
console.log('Server returned teacher options for class ' + $("#classSelector").find(":selected").text() + 'and level ' + selectedLevel, data);
// data now contains the array of options for teacherSelector.
// I'm going to assume you know how to loop through them and populate teacherSelector
}
});
});
Cool. Now, let's get one of our PHP scripts setup. I'm going to assume you are using a MySQL database, and for this example I am not going to include any of the code you need to use to cleans and secure the script (you can find that all over other questions on SO). Most of the PHP script is a straight copy/paste from W3Schools.
<?php
header('Content-Type: application/json'); // We are going to send a JSON response
// Server connection info
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$selectedValue = $_REQUEST['selectedValue'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM levels WHERE class = " . $selectedValue; // THIS IS AN EXAMPLE. IN PRODUCTION, ALWAYS CLEAN USER INPUT FIRST.
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$results = array();
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
echo json_encode($results);
} else {
echo json_encode("0 results");
}
$conn->close();

how to populate dropdown menu item from databaes

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!!

Categories