populate multiple select dropdownlist using Ajax - javascript

Im trying to populate my multiple dropdown list using ajax. but its not working. this dropdown list is dependent on another dropdown list which is single selection dropdown list.
Html Code is :
<div class="form-group">
<label for="InputGender">Select Course</label>
<div class="input-group">
<select class="form-control" name="sub_id" id="sub_id">
<option value="">Select Course Name</option>
<?php
while ($row = $result->fetch_row()) {
?>
<option value="<?php echo $row[0]; ?>"><?php echo $row[1]; ?></option>
<?php } ?>
</select>
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label>Second Level Category</label><br />
<select id="chap_id" name="chap_id[]" multiple class="form-control">
</select>
</div>
Ajax Code is:
$(document).ready(function(){
$("#sub_id").change(function(){
var id = $(this).val();
$.ajax({
url: 'AddQuestionAjax.php',
type: 'post',
data: {subId:id},
dataType: 'json',
success:function(response){
var len = response.length;
$("#chap_id").empty();
$("#chap_id").append("<option value=''>Select Chapter</option>");
for( var i = 0; i<len; i++){
var cid = response[i]['id'];
var cname = response[i]['name'];
$("#chap_id").append("<option value='"+cid+"'>"+cname+"</option>");
}
}
});
});
});
below is JSON response or the code writted in AddQuestionAjax.php file
<?php
session_start();
require 'conn.php';
$tSubId = $_POST['subId']; // department id
$sql = "SELECT * FROM chapter WHERE Subject_subId=".$tSubId;
$result = mysqli_query($con,$sql);
$sub_arr = array();
while( $row = mysqli_fetch_array($result) ){
$sid = $row['idChapter'];
$sname = $row['chapName'];
$sub_arr[] = array("id" => $sid, "name" => $sname);
}
// encoding array to json format*/
echo json_encode($sub_arr);
?>

I don't know about PHP section code but i've tried this. Just a example what you are doing here and it is working perfectly
<div class="form-group">
<label for="InputGender">Select Course</label>
<div class="input-group">
<select class="form-control" name="sub_id" id="sub_id">
<option value="">Select Course Name</option>
<option value="1">1</option>
</select>
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label>Second Level Category</label>
<br />
<select id="chap_id" name="chap_id[]" multiple class="form-control">
</select>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$("#sub_id").change(function() {
var response = [{
id: 1,
name: 'a'
}, {
id: 2,
name: 'b'
}];
for (var i = 0; i < response.length; i++) {
var cid = response[i]['id'];
var cname = response[i]['name'];
$("#chap_id").append("<option value='" + cid + "'>" + cname + "</option>");
}
});
});
</script>
you also need to parse the JSON before looping thorough your records. Which can be done by this
var res = JSON.parse(response);
Then parhaps you can add your records in select picker

Related

How to populate multiple textbox based on dropdown selection?

I have to populate my 2 textboxes based on the dropdown value from a single table.
Here is my table structure:
When I select the product name from the dropdown I want the 2 textboxes values to populate 1.sale_price 2.tax_amt. I have already populated the dropdown value from DB, please help me with the textboxes value.
DROPDOWN:
<select name="select_services[]" class="form-control select_services">
<option value="">--SelectProduct--</option>
<?php
$sql= "SELECT * from products where delete_status='0' ORDER BY id DESC";
$result=$conn->query($sql);
foreach ($result as $r_service) { ?>
<option value="<?php echo $r_service['id'];?>"><?php echo $r_service['name'];?></option>
<?php } ?>
</select>
Textboxes that I need to populate
<div class="col-sm-2">
<input type="text" class="form-control" id="unit_price" name="unit_price[]" placeholder="Sale Price" required>
</div>
<div class="col-sm-2">
<input type="text" class="form-control" id="tax" name="tax[]" placeholder="Tax" required>
</div>
JAVASCRIPT
<script type="text/javascript">
$('div.mydiv').on("change",'select[name^="select_services"]',function(event){
var currentRow=$(this).closest('.subdiv');
var drop_services= $(this).val();
$.ajax({
type : "POST",
url : 'ajax_service.php',
data : {drop_services:drop_services },
success: function(data){
currentRow.find('input[name^="quantity"]').val(0);
currentRow.find('input[name^="unit_price"]').val(data);
var quantity =currentRow.find('input[name^="quantity"]').val();
var unitprice=currentRow.find('input[name^="unit_price"]').val();
var total = parseInt(quantity) * parseInt(unitprice);
currentRow.find('input[name^="total"]').val(total);
//var total=+currentRow.find('input[name^="total"]').val(total);
// $('#subtotal').val(total);
var sum = 0;
$('.total').each(function() {
if($(this).val()!='')
{
sum += parseInt($(this).val());
}
});
var sub = $('#subtotal').val(sum);
var fsub = $('#final_total').val(sum);
var tot_commi = 0;
}
});
});
</script>
PHP: ajax_service.php
<?php
include('connect.php');
if(isset($_POST['drop_services']))
{
$sql_service1 ="SELECT * FROM products WHERE id = '".$_POST['drop_services']."'";
$result1=$conn->query($sql_service1);
$service1 = mysqli_fetch_array($result1);
echo $service1['sale_price']; exit;
}
?>

How i get the values in select option using javascript

I am fetching acno from table when i select a party name in option.I have so far tired i get the acno from the table but it is not place in the option box.
My controller code:
public function get_states2()
{
$name = $this->input->post('name');
$result = $this->db->query("SELECT TAcNo FROM tipup_payment LEFT OUTER JOIN parmaster on parmaster.pcode = tipup_payment.TName WHERE PName='$name' ")->result_array();
echo json_encode($result);
}
My View page code:
<div class="col-md-6">
<div class="form-group form-group-xs">
<div class="col-lg-9">
Party Name:
<select class="form-control countries" name="City">
<option></option>
<?php foreach ($PName as $row ): ?>
<option value="<?php echo trim($row['PName']); ?>"><?php echo trim($row['PName']); ?></option><?php endforeach ?>
</select>
</div>
</div>
<div class="form-group form-group-xs">
<div class="col-lg-9">
AcNo:
<select multiple="multiple" style="height: 85px;" id="Name" class="form-control states">
<option value=""></option>
</select>
<?php echo form_error('Area', '<div class="text-danger">', '</div>'); ?>
</div>
</div>
<div id="item">
<input type="checkbox" name="item">With Details</center></div>
</div>
</div>
My Script Code:
<script type="text/javascript">
$(document).ready(function(){
$('.countries').change(function(){
var name = $('.countries').val();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>Tieup/get_states2",
data:{name:name},
datatype: 'json',
success: function (data) {
/*get response as json */
alert(data);
var result = jQuery.parseJSON(data);
var no = result.TAcNo;
$("#Name").val(no);
/*ends */
}
});
});
});
</script>
This is my view page when i select a party name it should display the acno in acno option box( it down the party name).
give a class or id to ur dropdown
ur html
<select class="product">
</select>
ur jquery code
loop through all ur value and set it in ur option value one by one and at the end inject all ur html to ur select option using .html()
var value = [{"TAcNo":"341"}]
var options = '<option value="">Select</option>';
$(value).each((index, item) => { //loop through your elements
console.log(item)
options += '<option value="'+item.TAcNo+'">'+item.TAcNo+'</option>';
});
$('.product').html(options);
Hope it helps
Solution
you need to trigger change like this to update select value
$("#Name").val(no).change();

Get ajax dropdown base on parent id return undefined in Laravel

I try to get list of city of my chosen state(province) and city names return as undefined
here is my controller methods
public function index(Request $request) {
$rajaongkir = new Rajaongkir\Domestic('xxxxxxxxxxxxxxx');
$province = $rajaongkir->province();
$origin = 152; //Jakarta
$destination = 178; // Kediri
$weight = 1;
$courier = 'tiki'; // jne, tiki, pos
$cost = $rajaongkir->cost($origin, $destination, $weight, $courier);
return view('front.raja', compact('province', 'cost'));
}
public function getCityList($province)
{
$rajaongkir = new Rajaongkir\Domestic('xxxxxxxxxxxxxxx');
$city = $rajaongkir->city($province);
return response()->json($city);
}
my blade codes:
<form action="">
{{csrf_field()}}
<select name="province" id="">
<option class="form-control" value="">Select Province</option>
#foreach ($province->data as $info)
<option value="{{$info->province_id}}">{{$info->province}}</option>
#endforeach
</select>
<select name="city" id="">
<option class="form-control" value="">Select City</option>
</select>
<div style="margin-top: 30px;">
Destination:
{{$cost->meta['destination']->province}},
{{$cost->meta['destination']->type}},
{{$cost->meta['destination']->city_name}},
{{$cost->meta['destination']->postal_code}}.
#foreach($cost->data as $option)
<h3>{{$option->code}} <small>{{$option->name}}</small></h3>
#foreach($option->costs as $cost)
#foreach($cost->cost as $c)
<label class="radio">
<input name="post" value="{{ $c->value }}" type="radio">{{$cost->service}} / {{ $c->value }} Rp - {{ $c->etd }} hari #if(!empty($c->note))- {{ $c->note }} #endif
</label>
#endforeach
#endforeach
#endforeach
</div>
<button type="submit" class="btn btn-default">save</button>
</form>
my javascript codes:
<script type="text/javascript">
$(document).ready(function() {
$('select[name="province"]').on('change', function() {
var provinceID = $(this).val();
if(provinceID) {
$.ajax({
url: '{{ url('get-city-list') }}/'+encodeURI(provinceID),
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option class="form-control" value="'+ value['city_id'] +'">'+ value['city_name'] + ' - ' + value['type'] +'</option>');
});
}
});
}else{
$('select[name="city"]').empty();
}
});
});
</script>
here is result of my codes:
If I add alert(JSON.stringify(value, null, 4)); before append will
return:
Here is what I try to achieve in total Logic:
Choose Province
Get City list of that Province
Get Id of that city and add it as my $destination in Index function $destination = 178; // Kediri
The point is all this has happen with ajax, why? because I try to use
this form in my cart before checkout so when I hit checkout button is
already included shipping price.
Looking at your comments, it appears you are trying to iterate the wrong object:
Use:
$.each(data.data
Instead of just:
$.each(data
This is because your data from the ajax success comes back as:
{
code:200,
data:[
...etc.
],
error: ...etc.
}

How to filter multicolumn mysql data and display on the webpage using php and ajax

Recently i have asked same question but this is improved one.
i have some select options on my webpage and as someone selects option i want to get data from database for the same. i tried to do but i am geting data for only one select . what if i want to get data with combination of 3 select fields . how can i achieve this. please help !!!
here is my html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Filter</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" >
<link rel="stylesheet" href="css/style.css">
<link href="https://fonts.googleapis.com/css?family=Exo+2" rel="stylesheet">
</head>
<body>
<div id="rooms"></div>
<div class="container main-section" id="main">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="location">Location:</label>
<select name="location" id="location" class="form-control">
<option value="">Select</option>
<option value="candolim">Candolim</option>
<option value="calangute">Calangute</option>
<option value="baga">Baga</option>
<option value="anjuna">Anjuna</option>
<option value="morjim">Morjim</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="stay_type">Property Type:</label>
<select name="stay_type" id="stay_type" class="form-control">
<option value="">Select</option>
<option value="hotel">Hotel</option>
<option value="villa">Villa</option>
<option value="studio">Studio</option>
<option value="resort">Resort</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="room_type">Room Type:</label>
<select name="room_type" id="room_type" class="form-control">
<option value="">Select</option>
<option value="standard">Standard</option>
<option value="deluxe">Deluxe</option>
<option value="suit">Suit</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group"><br>
<input type="submit" name="submit" value="Search" class="btn btn-success">
</div>
</div>
</div>
</div>
<div class="display">
</div>
<script src="js/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="js/script.js" type="text/javascript"></script>
</body>
</html>
and this is my script --
$(document).ready(function(){
getAllRooms();
function getAllRooms(){
$.ajax({
url:'action.php',
method: 'POST',
data:{rooms:1},
success:function(response){
$('.display').html(response);
}
});
}
$('#location').change(function(){
var location = $(this).val();
$.ajax({
url:'action.php',
method: 'POST',
data:{location:location},
success:function(response){
$('.display').html(response);
}
});
});
});
and finally here is my action.php
<?php
$conn=mysqli_connect('localhost','cms_user','12345','rooms');
if (isset($_POST['rooms']) || isset($_POST['location'])){
if (isset($_POST['rooms'])){
$query_all = "SELECT * FROM rooms ORDER BY rand() ";
}
if(isset($_POST['location'])){
$location = $_POST['location'];
$query_all = "SELECT * FROM rooms WHERE location = '$location' ORDER BY rand() ";
}
$query_run = mysqli_query($conn,$query_all);
if (mysqli_num_rows($query_run)>0){
while ($row = mysqli_fetch_array($query_run)){
$room_id = $row['id'];
$room_name = $row['name'];
$location = $row['location'];
$stay_type = $row['stay_type'];
$room_type = ucfirst($row['room_type']);
$image = $row['image'];
$price = $row['price'];
echo "
<div class='container rooms'>
<div class='row'>
<div class='col-md-4'>
<img src='img/$image' alt='room' width='100%'>
</div>
<div class='col-md-6'>
<h2>$room_name</h2>
<p>$stay_type</p>
<h4 class='text-success'>$location</h4>
</div>
<div class='col-md-2'>
<br><br><br><br>
<h4 class='text-primary'>$room_type</h4>
<h4>Rs : $price </h4>
<a href='#'><input type='submit' name='book' value='Book Now' class='btn btn-success'></a>
</div>
</div></div>
";
}
} else {
echo "<center><h3>No Properties available</h3></center>";
}
}
?>
Thanks !
In your jquery, you should have a .change function for all 3 select boxes - when any of the select boxes change, grab and send all 3 values to your php page.
$(document).ready(function(){
getRooms();
function getRooms(){
var location = $('#location').val();
var stay_type = $('#stay_type').val();
var room_type = $('#room_type').val();
$.ajax({
url: 'action.php',
method: 'POST',
data: {
"location" : location,
"stay_type" : stay_type,
"room_type" : room_type,
},
success:function(response){
$('.display').html(response);
}
});
}
$('#location').change(function(){
getRooms();
}
$('#room_type').change(function(){
getRooms();
}
$('#stay_type').change(function(){
getRooms();
}
});
In your php page, get the value of all 3 possible post variables and start building your query based on those values. It helps to split up the sql statement into parts and then just combine them at the very end.
# setting parameters from the post
$room_type = isset($_POST['room_type']) ? $_POST['room_type'] : '';
$location = isset($_POST['location']) ? $_POST['location'] : '';
$stay_type = isset($_POST['stay_type']) ? $_POST['stay_type'] : '';
# defaults
$select = "SELECT * FROM rooms";
$where = " WHERE 1 = 1"; # to have a default where that is always true
$order_by = " ORDER BY rand()"; # you can always change the order by this way
if ($room_type != '') {
$where .= " AND room_type = '$room_type'";
}
if ($location != '') {
$where .= " AND location = '$location'";
}
if ($stay_type != '') {
$where .= " AND stay_type = '$stay_type'";
}
$sql = $select . $where . $order_by;
/* execute query using the $sql string and output results here */
This will also not require you to set a rooms value since it will still execute a query for all items.
If you want PHP to treat $_GET/$_POST['select2'] as an array of options just add square brackets to the name of the select element like this:
Then you can access the array in your PHP script
<?php
header("Content-Type: text/plain");
foreach ($_GET['select2'] as $selectedOption)
echo $selectedOption."\n";
$_GET may be substituted by $_POST depending on the

Use value from a form in a redirect button outside the form

Fetch selected value from dropdown which is in one form and onClick of the button outside the form send the value to php page
<div class="drpvendorname">
<font style="color: white;">
<label>Distribution Point:</label>
</font>
</div>
<select class="form-control" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option onClick="distribution('.$result['pointshortname'].')" value="' .$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
</form><!--form1 ends here-->
<form action="../customer/form.php"><!--form2 starts here-->
<button class="btn pos7" name="abc" method="GET" style="margin-left:5%;">New Customer</button>
</form><!--form2 ends here-->
<div class="dailybreakupbtn">
<input class="btn" type="submit" id="dailybreakupbutn" name="dailybreakup" value="Enter Daily Breakup" onClick="distribution(<?=$pointname?>)"/>
</div>
<?php
if(isset($pointname)){
?>
<script type="text/javascript">
function distribution(pointname){
var pointname;
window.location.href="dailybreakup.php?query=" +pointname;
}
</script>
<?php
}
?>
I have tried this sending selected dropdown box value to next page using function name distribution
I ended sending undefined to the next page.
can any one help me sending the selected value to the next page with out putting the button in the <form>
May this will be help you :)
Html code:
<form action= "" method= "post">
<select class="form-control drpvendor" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option value="'.$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
</form>
JQuery Code:
$(doucment).on('change','.drpvendor',function(){
var data=$(this).attr('selected','selected');
$.ajax({
url: "dailybreakup.php",
data:'query='+ data,
type: "POST",
success: function(data) {
window.location.href='customer/form.php';
}
});
});
Use code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> // please link the path or use cdn
<script type="text/javascript">
function call_me(){
var pointname=document.getElementById("drpvendor").value;
alert(pointname); // comment it after testing
window.location.href="dailybreakup.php?query=" +pointname;
}
</script>
<form>
<select class="form-control" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option value="' .$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
<input type="button" onclick="call_me()"/>
</form><!--form1 ends here-->
Note : 1) Code is not tested
2) use your select id instead of your_select_id
3) check variable

Categories