How can I get a dependent dropdown selected value? - javascript

I am new at development, right now I am learning laravel 9 and I am trying to get a dependent dropdown selected value. Here is my blade file:
<div class="form-group">
<label for="vendor_state">State</label>
<select class="form-control" style="color: #000;" id="vendor_state" name="vendor_state">
<option selected disabled>Select State</option> #foreach ($states as $state)
<option value="{{ $state->id }}" #if(!empty($state->id==$vendorDetails['state'])) selected #endif>{{ $state->name }}</option> #endforeach
</select>
</div>
<div class="form-group">
<label for="vendor_city">City</label>
<select class="form-control" style="color: #000;" id="vendor_city" name="vendor_city"></select>
</div>
And here is the script:
<script type="text/javascript">
$(document).ready(function () {
$('#vendor_state').on('change', function () {
var stateId = this.value;
$('#vendor_city').html('');
$.ajax({
headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{ route('cities') }}?state_id='+stateId,
type: 'get',
success: function (res) {
var dropdown = $('#vendor_city');
dropdown.html('<option selected disabled value="">Select City</option>');
$.each(res, function (key, value) {
dropdown.append('<option value="' + value.id + '">' + value.name + '</option>');
});
}
});
});
});
</script>
For now, I can save the values of the state and the city in the database and get the selected value of the state. How can I get the selected value of the city?
I tried storing the selected value in dropdown var and display it using if condition inside the option value of the script.

Some time ago, I wrote a similar script for another system. Chose country, then a dropdown with Regions(states) list appears. Upon Choosing a region, a list of Departments (Cities) appears.
Note:
In the database, I have relations from Regions (states) to Countries and from Departments to regions. I.e.:
In the Regions database table, I have a field named "country_id", and in the Departments table I have a column "region_id"
My code was as follows:
The main page with the dropdowns
//Country drop-down select
<select style="max-width:150px;" name="country_id" id="country-list" onChange="getRegion(this.value);">
//Options with list of countries names and ID in foreach loop
<option value="' . $country->id . '">' . $country->name . '</option>
</select>
<select name="region_id" id="region-list" onChange="getDepartment(this.value);">
<option value=""><?= $langs->trans('SelectRegion') ?></option>
</select>
<select name="department_id" id="department-list" class="demoInputBox">
<option value=""><?= $langs->trans('SelectDepartment') ?></option>
</select>
The AJAx function:
function getRegion(val) {
$.ajax({
type: "POST",
url: "region.inc.php",
data: 'country_id=' + val,
success: function (data) {
$("#region-list").html(data);
}
});
}
function selectCountry(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
function getDepartment(val) {
$.ajax({
type: "POST",
url: "department.inc.php",
data: 'region_id=' + val,
success: function (data) {
$("#department-list").html(data);
}
});
}
function selectRegion(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
"region.inc.php" is:
$country_id = $_POST['country_id'];
<option value=""><?= $langs->trans('SelectRegion') ?></option>
$regions_array = function_to_get_regions_ids_and_names_in_array
foreach ($regions_array as $result) {
print '<option value="' . $result->region_id . '">' . $result->department_id . '</option>';
}
"departments.inc.php"
$region_id = $_POST['region_id'];
$departments_array = function_to_get_departments_ids_and_names_in_array
<option value=""><?= $langs->trans('SelectDepartment') ?></option>
foreach ($departments_array as $result) {
print '<option value="' . $result->department_id . '">' . $result->department_name . '</option>';
}

Related

keep old select value while validation failed in ajax in laravel

In my Laravel project I have an appointment form where patient can choose a doctor after choosing a branch from the dropdown list. I use AJAX for doing the functionality.
Now after any validation failed all the form value restored accept the doctor.
But I want to automatically restored that selected doctor after validation failed.
html form
<select class="form-control appointment_form_searchField" id="appointment_branch" name="appointment_branch" style="font-size:.7em;;width: 100%;">
<option value="">Select Branch</option>
#if($_SESSION['branch'] != null)
#foreach($_SESSION['branch'] as $data)
<option value="{{ $data->id }}">{{ $data->name }}</option>
#endforeach
#endif
</select>
<select class="form-control" id="appointment_doctor" name="appointment_doctor" style="font-size:.7em;padding: 0.6500rem .75rem;width: 100%;">
<option value="">Select Doctor</option>
</select>
AJAX
jQuery(".appointment_form_searchField").change(function() {
var branch_id = $("#appointment_branch").val();
var token = $('input[name=_token]').val();
if(branch_id.trim() != '')
{
jQuery.ajax({
url:"{{ url('/filter_doctor') }}",
type: 'GET',
data: {_token :token, branch_id : branch_id},
success:function(msg){
$('#appointment_doctor option').remove();
trHTML = '';
trHTML += "<option value=''>Select Doctor</option>";
msg.forEach(function(item){
trHTML += "<option value='"+item.id+"'>" + inputem.name + "</option>";
});
$('#appointment_doctor').append(trHTML);
}
});
}
});
controller
public function filter_doctor(Request $request)
{
$branch_id = $request->branch_id;
$query = DB::table('service_doctors');
$query->select('doctor_id','inactive_dates_in_this_month');
if($branch_id != '0')
$query->where('branch_id','=', $branch_id);
$result_time = $query->get();
$array_doctor_id = $result_time->pluck('doctor_id');
$doctor = Doctor::whereIn('id', $array_doctor_id)->get();
return $doctor;
}
Anybody Help please ? Thanks in advance
If you are using Laravel 5 then you can do something like this.
In your form add missing details appointment_branch and appointment_doctor like below.
The Request::old() option load previous posted value in from hence you need to first select old value for appointment_branch'. Also temporary storeold appointment_doctorvalue indata-oldid` so the script can identify which was the old value submitted by user and can load this select box when document is ready.
<select class="form-control appointment_form_searchField" id="appointment_branch" name="appointment_branch" style="font-size:.7em;;width: 100%;">
<option value="">Select Branch</option>
#if($_SESSION['branch'] != null)
#foreach($_SESSION['branch'] as $data)
<option value="{{ $data->id }}" {{ Request::old()?(Request::old('appointment_branch')==$data->id?'selected="selected"':''):'' }}>{{ $data->name }}</option>
#endforeach
#endif
</select>
<select class="form-control" id="appointment_doctor" name="appointment_doctor" style="font-size:.7em;padding: 0.6500rem .75rem;width: 100%;" data-oldid="{{ Request::old()?Request::old('appointment_doctor'):'' }}">
<option value="">Select Doctor</option>
</select>
And then write your script like below.
<script>
jQuery(document).ready(function($){
if(jQuery("#appointment_doctor").data('oldid')!='' && typeof(jQuery("#appointment_doctor").data('oldid'))!="undefined"){
jQuery(".appointment_form_searchField").change();
}
});
jQuery(".appointment_form_searchField").change(function() {
var branch_id = $("#appointment_branch").val();
var token = $('input[name=_token]').val();
if(branch_id.trim() != '')
{
jQuery.ajax({
url:"{{ url('/filter_doctor') }}",
type: 'GET',
data: {_token :token, branch_id : branch_id},
success:function(msg){
$('#appointment_doctor option').remove();
trHTML = '';
trHTML += "<option value=''>Select Doctor</option>";
msg.forEach(function(item){
trHTML += "<option value='"+item.id+"'>" + inputem.name + "</option>";
});
$('#appointment_doctor').append(trHTML);
}
if(jQuery("#appointment_doctor").data('oldid')!='' && typeof(jQuery("#appointment_doctor").data('oldid'))!="undefined"){
jQuery('#appointment_doctor').val(jQuery("#appointment_doctor").data('oldid')); //select the old doctor id here
}
});
}
});
</script>

Laravel - Ajax call not responding

I am trying to Post the data from the dropdown box and sent the request using Ajax. It is working fine on the localhost but its not working properly on the shared-hosting. I have 3 dropboxes and the value changes according to the values selected from its parent dropbox. For Eg: Car Make (Audi) -> Car Model -> (A4, A5, Q5 etc.. audi models) ->year (19XX - 2019)
I am only able to select the Make, but I am not able to get any data from the Car Make selected.
home.blade.php
<div class="form-group">
<select class="form-control dynamic" name="Make" id="Make" data-dependent='Model'>
#foreach($carLists as $carMake)
<option value="{{$carMake->Make}}">{{$carMake->Make}} </option>
#endforeach
</select>
</div>
<div class="form-group">
<select class="form-control dynamic" name="Model" id="Model" data-dependent='Year'>
<option value="">Select Model</option>
</select>
</div>
<div class="form-group">
<select class="form-control dynamic" name="Year" id="Year" data-dependent='Body'>
<option value="">Select Manufacturing year</option>
</select>
</div>
<script>
$(document).ready(function(){
$('.dynamic').change(function(){
if($(this).val() != '')
{
var select = $(this).attr("id");
var value = $(this).val();
var dependent = $(this).data('dependent');
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('pagescontroller.fetch') }}",
method:"POST",
data:{select:select, value:value, _token:_token, dependent:dependent},
success:function(result)
{
$('#'+dependent).html(result);
}
})
}
});
$('#Make').change(function(){
$('#Model').val('');
$('#Year').val('');
$('#Make').val($(this).val());
console.log($('#HidMake'));
});
$('#Model').change(function(){
$('#Year').val('');
});
});
</script>
PageController.php
class PagesController extends Controller
{
function fetch(Request $request)
{
$select = $request->get('select');
$value = $request->get('value');
$dependent = $request->get('dependent');
$data = DB::table('carLists')
->where($select, $value)
->groupBy($dependent)
->get();
$output = '<option value="">Select '.ucfirst($dependent).'</option>';
foreach($data as $row)
{
$output .= '<option value="'.$row->$dependent.'">'.$row->$dependent.'</option>';
}
echo $output;
}
Routes (web.php)
Route::post('inc/sidebar/fetch', 'PagesController#fetch')->name('pagescontroller.fetch');
I am being trying alot but no clue whats going wrong here, however, on the localhost its working fine.
thanks for the time.
Try changing the url to
var url = APP_URL + '/inc/sidebar/fetch';
and set header
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
instead of
var _token = $('input[name="_token"]').val();
and let me know, the result you are getting for this.

getting select box to display selected value in different select box

I have two select boxes in which I want to select a value for one and the second select box should get same value.
Currently I am passing id and want my designation also to pass to ajax. Can I know how this can be implemented via ajax. Any help will be highly appreciated.
<select name="designation" class="form-control" id="desig" >
<option value="">Select a Designation/Role</option>
<?php
$sql = mysql_query("SELECT id, designation FROM tbl where status =1 and designationtype_id = 1 ");
while ($rows = mysql_fetch_assoc($sql)){
echo "<option value=" . $rows['id'] . ">" . $rows['designation'] . "</option>";
}
?> <select name="dd" id="dd" class="form-control" disabled>
<option value=""></option>
</select>
My AJAX,
<script type="text/javascript">
$(document).ready(function() {
$("#desig").change(function() {
var id = $(this).val();
var dataString1 = 'id=' + id;
var des = $(this).val();
var dataString2 = 'designationname=' + des;
$.ajax({
type: "POST",
url: "escalation_ajax.php",
data: dataString,
cache: false,
success: function(html) {
var data = html.split(",");
$('#rephead').val(data[0]);
}
});
});
});
</script>
escalation_ajax.php
<?php
if ($_POST['id'])
{
if ($_POST['des'])
{
$des_id = $_POST['id'];
$designation = $_POST['des'];
$sql = mysql_query("SELECT designation_id, reporting_head FROM aafmindia_in_sbi.tbl_reporting_head WHERE status=1 and reporting_head_for='$des_id'");
if ($sql === FALSE)
{
trigger_error('Query failed returning error: ' . mysql_error() , E_USER_ERROR);
}
else
{
while ($row = mysql_fetch_array($sql))
{
$id = $row['designation_id'];
$reporting_head = $row['reporting_head'];
echo '<option value="' . $id . '">' . $reporting_head . '</option>' . ',' . '<option value="' . $des_id . '">' . $designation . '</option>';
}
}
}
}
?>
What you could do, is have the second select (the one that needs the same value as the first) in a seperate file that you load via AJAX.
AJAX function:
function selection()
{
var selectValue=$("select#dd option:selected").val();
$.ajax({
type : "POST",
url : "escalation_ajax.php",
data : { id : selectValue },
success: function (html) {
$("#secondSelectorDiv").html(html);
}
})
}
What this does, is that when the selection() function is called, it will post the selected value of the first select to "escalation_ajax.php". It will then load that page into an element (div element in my example) with the id "secondSelectorDiv".
The html for the select with the function (which I will call onchange in this example), can look like this:
<select id="dd" onchange="selection();">
<option value=""></option>
</select>
<div id="secondSelectorDiv"></div>
Now in escalation_ajax.php you can retrieve the post variable and use it to look for the id in question for the second select.
<?php
$id=$_POST['id'];
/*
If you're using the id to fetch something in your database,
which it looks like you're doing, then use the post variable
to fetch your rows and build the select from that.
*/
$sql="SELECT * FROM table_name WHERE id='$id'";
$result_set=mysql_query($sql);
$row=mysql_fetch_array($result_set);
$count=mysql_num_rows(result_set);
$counter=0;
//this is the id you will check for in order to see what's to be selected
$idToCheck=$row['id'];
?>
<select id="dd2">
while($count > $counter)
{
counter++;
echo '<option value=""'; if($idToCheck == $id){ echo 'selected="selected"'; } echo '></option>';
}
?>
If you want the second select to be displayed before the first select has a value, you can simply just call an AJAX function that loads in the second select on page load.
IMPORTANT!: You should really switch to mysqli_* or PDO instead of using the deprecated mysql_*. You should at the very least look into sanitizing your inputs.

add list item depending on another list

i have two list box for countries and states. when i click on a country for ex. India, the corresponding states appears in the states list. but the same should happen for more than one country. if i select two countries, the states of the both countries should be added in the states list.
javascript code for countries list-
$('#pcountries').on('change', function() {
var country_id = this.value;
$.ajax({
type: "POST",
url: "php_includes/select_list_pstate.php",
data: 'country_id=' + country_id,
success: function (result) {
$("#pstate").append(result);
}
});
});
php code-
if ($_POST['country_id']) {
$country_id = $_POST['country_id'];
if ($country_id != '') {
$states_result = $db_conx->query('select * from states where countryId=' . $country_id . '');
$options = "<option value=''>Any</option>";
while ($row = $states_result->fetch_assoc()) {
$options .= "<option value='" . $row['stateId'] . "'>" . $row['state'] . "</option>";
}
echo $options;
}
}
Multiple Select returns an array you need to use in instead of = in query like this
$states_result = $db_conx->query("select * from states where countryId IN (".implode(',',$country_id ).")";);
var selectedValues = $('#multipleSelect').val();
console.log(selectedValues)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="multipleSelect" multiple="multiple">
<option value="1" selected>Text 1</option>
<option value="2" selected>Text 2</option>
<option value="3">Text 3</option>
</select>

select box using ajax and CakePHP

I'm trying to get data related to parent data from select options , and here's my add.ctp
<select name="id" id="category">
<option value="hide">-- اختر مجموعة الصنف --</option>
<?php foreach ($warehouseCategoriesItems as $warehouseCategoriesItem): ?>
    <option value="<?php echo $warehouseCategoriesItem; ?> " ><?php echo $warehouseCategoriesItem; ?></option>
<?php endforeach; ?>
</select>
<select name="id" id="item">
<option>-- اختر الصنف-- </option>
</select>
and here's the script for that :
<script type="text/javascript">
var types_list = $('#item');
$('#category').change(function(){
carId = $(this).val();
$.ajax({
type: "GET",
url: '../warehouse-add-orders-items-form7/add/' + carId ,
data: { 'carId': carId },
success: function( response ) {
types_list.empty();
types_list.append(
$("<option></option>")
.text('-- إختر نوع --')
.val('')
);
$.each(response, function(id, name) {
types_list.append(
$("<option></option>")
.text(response[id].category_item_name)
.val(response[id].warehouse_categories_items_id)
);
});
types_list.trigger('chosen:updated');
}
});
});
.There's relationship between the category parent and the child items , but i'm getting the child with null values each time and the parent back with it's value .
can any one tell me the problem here ?

Categories