Laravel chained dropdown selection using jquery ajax - javascript

I'm using laravel 5.6 and I've made dropdown selection but it didn't work. I choosed a province in dropdown menu provinces but the menu city not shown up the data of cities.
This is my controller :
public function province()
{
$prov = Province::orderBy("provinsi.id","ASC")
->pluck("name","id");
return view('auth.register',compact('prov'));
}
public function cities($id)
{
$city = City::where("id_provinsi","=",$id)
->pluck("city_name","id");
return json_encode($city);
}
This is my route:
Route:: get('/register', 'Auth\RegisterController#province');
Route:: get('/register/cities/{id}', 'Auth\RegisterController#cities');
This is my view:
<div class="form-group row">
<label for="prov" class="col-md-4 col-form-label text-md-right">{{ __('Provinsi') }}</label>
<div class="col-md-6">
<select name="prov" class="form-control">
<option value="">=== Choose Province ===</option>
#foreach ($prov as $key=>$value)
<option value="{{$key}}">{{$value}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label for="city" class="col-md-4 col-form-label text-md-right">{{ __('City') }}</label>
<div class="col-md-6">
<select name="cities" class="form-control"> </select>
</div>
</div>
This is my javascript:
<script type="text/javascript">
$(document).ready(function()
{
$('select[name="prov"]').on('change', function() {
var provID = $(this).val();
if(provID) {
$.ajax({
url: '/register/cities/'+provID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="cities"]').empty();
$.each(data, function(key, value) {
$('select[name="cities"]').append('<option value="'+ key +'">'+ value +'</option>');
});
}
});
}else{
$('select[name="cities"]').empty();
}
});
});
</script>
I got the data json if I open the url /register/cities/(any province id) .

Make sure the response returned in
public function cities($id) { ... }
is in JSON format.
To do this check network log in your browser (in Firefox o Chrome F12 -> Net:XHR -> Response) or add a colsole.log(data) in the success callback.

in your view replace you second select
<select name="cities" class="form-control" id='cities'> </select>
your first select change this
<select name="prov" class="form-control">
<option value="">=== Choose Province ===</option>
#foreach ($prov as $key=>$value)
option value="{{$value->id}}">{{$value->name}}</option>
#endforeach
</select>
next changue in your controller
public function cities($id)
{
$city = City::where("id_provinsi",$id)->get()
return response()->json(['cities' => $city], 200);
}
changue this in your each inside ajax
$.each(data.cities, function(key, value) {
$('#cities').append('<option value="'+ value.id+'">'+ value.name +'</option>');
});
changue your url ajax for this
url:"{{ url('/register/cities/') }}/"+provID;

public function cities($id)
{
$city = City::where("id_provinsi","=",$id)
->pluck("city_name","id");
$html = view('city_list', compact('city'))->render();
return response()->json([
'html' => $html
]);
}
city_list.blade.php
<select name="city" class="form-control">
<option value="">=== Choose City===</option>
#foreach ($city as $key=>$value)
<option value="{{$key}}">{{$value}}</option>
#endforeach
</select>

Related

Dependent drop down list using ajax routes not working in production server

i have a dependent list selection for country, district then area using ajax and in a local environment they are working perfectly fine, but in my production server they are not working i have tried to inspect the page and the get routes are coming out with an empty array...
Html code is as follows:
<div class="form-group row">
<label class="col-lg-3 col-form-label">Country</label>
<div class="col-lg-9">
<select class="form-control" required name="country" id="country">
<option value="">--Select Country--</option>
#foreach ($contries as $country)
<option value="{{ $country->id }}">
{{ $country->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label">District</label>
<div class="col-lg-9">
<select class="form-control" required name="district" id="state">
</select>
</div>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label">Area</label>
<div class="col-lg-9">
<select class="form-control" required name="area" id="city">
</select>
</div>
</div>
</div>
my javascript is as follows:
<script type="text/javascript">
$(document).ready(function () {
$('#country').on('change', function () {
var countryId = this.value;
$('#state').html('');
$.ajax({
url: '{{ url('supper/getStates') }}?country_id='+countryId,
type: 'get',
success: function (res) {
$('#state').html('<option value="">---Select District---</option>');
$.each(res, function (key, value) {
$('#state').append('<option value="' + value
.id + '">' + value.district_name + '</option>');
});
$('#city').html('<option value="">---Select Area---</option>');
}
});
});
$('#state').on('change', function () {
var stateId = this.value;
$('#city').html('');
$.ajax({
url: '{{ url('supper/getCities') }}?state_id='+stateId,
type: 'get',
success: function (res) {
$('#city').html('<option value="">Select City</option>');
$.each(res, function (key, value) {
$('#city').append('<option value="' + value
.id + '">' + value.area_name + '</option>');
});
}
});
});
});
</script>
My controllers methods are as follows
public function getCountry()
{
$countries = Country::get(["name","id"]);
return $countries;
}
public function getDistrict(Request $request)
{
$districts = District::where("country_id",$request->country_id)
->get(["district_name","id"]);
return $districts;
}
public function getArea(Request $request)
{
$areas = Area::where("district_id",$request->state_id)
->get(["area_name","id"]);
return $areas;
}
and my routes are as follows it should be noted these routes belong to a group with a prefix of "supper"
Route::get('getStates', [AdminPropertyController::class, 'getDistrict'])->name('getStates');
Route::get('getCities', [AdminPropertyController::class, 'getArea'])->name('getCities');
and lastly in my AppServiceProvider i have added this code to force https in production server
public function boot()
{
if(env('APP_ENV') !== 'local') {
URL::forceScheme('https');
}
}
i have checked but i cannot find the problem, i need help.

laravel dynamic dropdown with hasMany relationship

how to show sub-category while selected category with hasMany relationship using javascript or jquery??
there my Parent Table
public function ChildrenRasHewan() {
return $this->hasMany(RasHewan::class,'jenis_hewan_id');
}
and this is my Child table a.k.a sub category
public function ParentJenisHewan() {
return $this->belongsTo(JenisHewan::class,'jenis_hewan_id','id');
}
this is what my controller look like :
public function index()
{
$this->data['adopsi'] = Adopsi::paginate(10);
return view('admin.dashboard.adopsi.index-adopsi', $this->data);
}
public function create()
{
$this->data['getStatusAdopsi'] = Adopsi::statusAdopsi();
$this->data['jenisHewan'] = JenisHewan::pluck('nama_jenis_hewan');
$this->data['rasHewan'] = JenisHewan::all();
return view('admin.dashboard.adopsi.create-adopsi',$this->data);
}
public function getRasHewan($id) {
$getRasHewan = DB::table('ras_hewans')->where('id',$id)->pluck('nama_ras_hewan','id');
return json_encode($getRasHewan);
}
this is my index view where i want to applied dynamic dropdown :
<div class="form-group">
<label for="jenis_hewan_id">Jenis Hewan</label>
<select name="jenis_hewan_id" id="jenis_hewan_id" class="form-control #error('jenis_hewan_id') is-invalid #enderror" placeholder="">
<option value="">Pilih Jenis Hewan</option>
#foreach ($jenisHewan as $data)
<option value="{{$data->id}}" type="text">{{$data->nama_jenis_hewan}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="ras_hewan_id">Ras Hewan</label>
<select name="ras_hewan_id" id="ras_hewan_id" class="form-control #error('ras_hewan_id') is-invalid #enderror" placeholder="" >
<option value="" selected disabled>Pilih Ras Hewan</option>
#foreach ($jenisHewan as $data)
#if($data->ChildrenRasHewan))
#foreach ($data->ChildrenRasHewan as $rasHewan )
<option value="{{$rasHewan->id}}">{{$rasHewan->nama_ras_hewan}}</option>
#endforeach
#endif
#endforeach
<select name="ras_hewan_id" id="ras_hewan_id" class="form-control"></select>
</select>
</div>
the js script :
<script>
$(function() {
$('select[name=service_id]').change(function() {
var url = '{{ url('service') }}' + $(this).val() + '/categories/';
$.get(url, function(data) {
var select = $('form select[name= category_id]');
select.empty();
$.each(data,function(key, value) {
select.append('<option value=' + value.id + '>' + value.name + '</option>');
});
});
});
});
</script>

Getting City list base on Selected Province Stored in database, in Edit Method, in laravel 7

How can I get city lists base on selected province, in Edit Method ?
Controller Code :
public function edit($id)
{
$user = User::find($id);
$provinces = DB::table('provinces')->get()->all();
$cities = DB::table('cities')->get()->all();
return view("management.profiles.edit", compact('user','provinces', 'cities'));
}
public function getCityList($province_id)
{
$cities = DB::table('cities')->where("province_id",$province_id)->get();
return response()->json($cities);
}
Routes :
Route::get('change/profile/update', 'ProfileController#update')->name('panel.profile.update');
Route::get('panel/management/get-city-list/{province_id}','Management\UserController#getCityList');
view :
<div class="row">
<div class="col-xl-6">
<div class="form-group">
<label for="province">Province :</label>
<select name="province" id="province" class="form-control">
<option value="">------------</option>
#foreach ($provinces as $province)
<option value="{{ $province->id }}" {{ $user->province == $province->id ? 'selected' : '' }}>{{ $province->name }}</option>
#endforeach
</select>
#error('province')
<div class="invalid-feedback"> {{ $message }}</div>
#enderror
</div>
</div>
<div class="col-xl-6">
<div class="form-group">
<label for="city">City :</label>
<select name="city" id="city" class="form-control" data-old-id="{{$user->city}}">
<option value="">-------------</option>
</select>
#error('city')
<div class="invalid-feedback"> {{ $message }}</div>
#enderror
</div>
</div>
</div>
Script :
<script type="text/javascript">
function load_cities() {
let provinceID = $('#province').val();
if (provinceID === null) {
id = $('#province').eq(0).val();
}
if (provinceID) {
$.ajax({
url: '/panel/management/get-city-list/' + encodeURI(provinceID),
type: "GET",
dataType: "json",
success: function (data) {
$("#city").empty();
$.each(data, function (key, value) {
let selected = null;
if ($('#city').data('old-id') && value.id == $('#city').data('old-id')) {
selected = 'selected';
}
let optionTag = `<option value="` + value.id + `" ` + selected + `>` + value.name + `</option>`;
$('#city').append(optionTag);
});
}
});
} else {
$("city").empty();
}
}
</script>
my problem is : when i edit user profiles, city and province filed can't be selected base on stored city and province id in databse. I don't know where my problem is !!!
You have to call load_cities() when province is selected and also call it by default
<select name="province" id="province" class="form-control" onchange="load_cities()">
also when page loads call load_cities()

when select category not show subcategory

This is controller file code
public function call_pageAjax($id)
{
$subcat = DB::table("sub_categories")->where("cat_id",$id)->pluck("sub_cat_nm","id");
return json_encode($subcat);
// return view('purchase.supplier.add_supplier',compact('subcat'));
}
This is javascript file
<script type="text/javascript">
$(document).ready(function() {
$('select[name="category"]').on('change', function() {
var catID = $(this).val();
if(catId) {
$.ajax({
url: '/purchase/supplier/add_supplier/ajax/'+ catID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="subcategory"]').empty();
$.each(data, function(key, value) {
$('select[name="subcategory"]').append('<option value="'+ key +'">'+ value +'</option>');
console.log(data);
});
}
});
}else{
$('select[name="subcategory"]').empty();
}
});
});
</script>
This is view file.
<div class="form-group row">
<label class="col-sm-2 col-form-label" style="text-align-last: right;">Category Name:</label>
<div class="col-sm-6">
<select class="form-control" id="category" name="category">
<option value=" ">----select Category----</option>
#foreach ($category as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label" style="text-align-last: right;">Sub Category Name:</label>
<div class="col-sm-6">
<select class="form-control" id="subcategory" name="subcategory">
</select>
</div>
</div>
i am trying to get subcategory when i click category on a page but not display subcategory. Subcategory is display in API but isn't show in the page...
You may use
//...
success: function(data){
//Log the data to the console so that
//you can get a better view of what the script is returning.
console.log(data);
$('#subcategory').empty();
$.each(data, function(key, value){
//Use the Option() constructor to create a new HTMLOptionElement.
var option = new Option(key, value);
//Convert the HTMLOptionElement into a JQuery object that can be used with the append method.
$(option).html(value);
//Append the option to our Select element.
$('#subcategory').append(option);
});
}

How to use many dynamic dropdown in forloop(laravel) in using javascript and ajax?

I am trying to do with multiple dynamic dropdown because I want to use it inside foreach loop.In my process, I have stage and status for each job title which I screentshot atttched at the below.I loop the job title and placed the dynamic dropdown stage and status inside the foreach loop.
The problem is that if I select stage, all the status is keep changing depending on the stage which i selected.I only want to effect the status which i selected the stage, for example like in my above photo, if i choose stage under "chinese traslator(listening,speaking)" job title, it should be effect only the status under his own stage, should not be effected the status under the "Cashier" job title.
Here is my code for the code which I'd done so far,
<?php
$jobmatches = \App\Models\Jobposition::where('require_position',$jobseekers->desire_position_1)->orderBy('free_or_paid','desc')->pluck('id');
?>
#foreach($jobmatches as $value)
<?php $job_list = \App\Models\Jobposition::where('id',$value)->first(); ?>
<div class="form-group">
<input type="checkbox" name="job_position[]" value="{{ $job_list['id']}}">
{{ $job_list['job_title']}}<br>
</div>
<div class="form-group">
<label for="title">Select Stage:</label>
<select name="stage[]" class="form-control" >
<option value="">--- Select Stage ---</option>
#foreach ($stages as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="title">Select Status:</label>
<select name="status[]" class="form-control">
</select>
</div>
#endforeach
and here is ajax code,
$(document).ready(function() {
$('select[name="stage[]"]').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/myform/ajax/'+stateID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="status[]"]').empty();
$.each(data, function(key, value) {
$('select[name="status[]"]').append('<option value="'+ key +'">'+ value +'</option>');
});
}
});
}else{
$('select[name="status[]"]').empty();
}
});
});
Any help would be highly appreciated.
Add a wrapping div to the group of interelated elements:
<div class="job-list">
<div class="form-group">
<input type="checkbox" name="job_position[]" value="{{ $job_list['id']}}">
{{ $job_list['job_title']}}<br>
</div>
<div class="form-group">
<label for="title">Select Stage:</label>
<select name="stage[]" class="form-control" >
<option value="">--- Select Stage ---</option>
#foreach ($stages as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="title">Select Status:</label>
<select name="status[]" class="form-control">
</select>
</div>
</div>
Then in your JS you can adjust your handler to only work with elements in that same group:
$(document).ready(function() {
$('select[name="stage[]"]').on('change', function() {
var stateID = $(this).val();
/* define the target select, use closest to go back up to the job-list parent,
* then pull the select element that is a child of it
*/
var $select = $(this).closest('.job-list').find('select[name="status[]"]');
if(stateID) {
$.ajax({
url: '/myform/ajax/'+stateID,
type: "GET",
dataType: "json",
success:function(data) {
$select.empty();
$.each(data, function(key, value) {
$select.append('<option value="'+ key +'">'+ value +'</option>');
});
}
});
}else{
$select.empty();
}
});
});
You can keep track of their index and access them with the correct index, like this:
$('select[name="stage[]"]').on('change', function() {
var stateID = $(this).val();
var index = $(this).index();
var statusElem = $('select[name="status[]"]').get(index);
...
statusElem.empty();
$.each(data, function(key, value) {
statusElem.append('<option value="'+ key +'">'+ value +'</option>');
});
...
statusElem.empty();
});
I haven't tested this, but I think it's because you're adding the same listener to every dropdown.
Instead try adding a different listener to each like so:
$(document).ready(function() {
$('select[name="stage[]"]').each(function(index) {
$(this).on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/myform/ajax/'+stateID,
type: "GET",
dataType: "json",
success:function(data) {
$(this).empty();
$.each(data, function(key, value) {
$(this).append('<option value="'+ key +'">'+ value +'</option>');
});
}
});
} else {
$(this).empty();
}
});
});
});

Categories

Resources