Laravel 5 multi dynamic dropdown - ajax

I'm trying to use the data of the first dropdown, to fill the second.
An example here:
https://gitlab.com/Bons/laravel5.3_dynamic_dropdown/blob/master/readme.md
Controller functon return data, but second dropdown is empty.
First dropdown:
<span>Country: </span>
<select style="width: 200px" class="country" id="id_country">
<option value="0" disabled="true" selected="true">-Select-</option>
#foreach($countries as $contry)
<option value="{{$contry->id_country}}">{{$contry->name}}</option>
#endforeach
</select>
linked dropdown:
<label>City
<select id="region" class="form-control input-sm" name="region_id">
<option value=""></option>
</select>
</label>
Script:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','.country',function(){
console.log("hmm its change");
var id=$(this).val();
console.log(id)
$.ajax({
type:'get',
url:'{!!URL::to('findRegions')!!}',
data:{'id':id},
success:function(data) {
console.log("success");
console.log(data.length);
console.log(data);
$.each(data, function(index,subCatObj){
// console.log(subCatObj.name)
$('#region').append(''+subCatObj.name+'');
});
},
error:function(){
console.log("error");
}
});
});
});
</script>
Route:
Route::get('/findRegions/','GirlsController#findRegions');
Controller function:
public function findRegions(Request $request){
$id=$request->id;
$regions=Region::select('name')
->where('id_country',$id)
->get();
dump($regions);
return $regions;
}

Here is how i did it,
in routes/web.php
Route::post('select-ajax', 'Main#selectAjax')->name('select-ajax');
in Controller : Main.php
public function __construct()
{
View::share('selectAllCountries', Country::pluck("name","id")->all());
}
public function selectAjax(Request $request)
{
if($request->ajax())
{
$getRegion = Region::where('id_country',$request->id)->pluck("nameOfTheRegion","id")->all();
$data = view('ajax-select',compact('getRegion'))->render();
return response()->json(['options'=>$data]);
}
}
then create a simple blade file name ajax-select.blade.php
<option selected disabled>--- Select Region---</option>
#if(!empty($getRegion))
#foreach($getRegion as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
#endif
Ajax call
{!! Form::select('country',[' '=>'--- Select Country ---']+$selectAllCountries,null,['class'=>'form-control']) !!}
{!! Form::select('region',[' '=>'--- Select Region---'],null,['class'=>'form-control']) !!}
<script>
$("select[name='country']").change(function(){
var id = $(this).val();
var token = $("input[name='_token']").val();
$.ajax({
url: "{{ route('select-ajax') }}",
method: 'POST',
data: {'id':id, '_token':token},
success: function(data) {
$("select[name='region']").html('');
$("select[name='region']").html(data.options);
},
error:function(){
alert("error!!!!");
}
});
});
</script>
Hope this helps

Related

old() does not work on dependent dropdown in Laravel blade

I have two dropdown list in my Laravel page. I am trying to get old value of the dependent dropdown list (categorylist.blade) and make it selected once I fill and post the data. It returns back to the same page if the validation has not successfully completed. I am able to get all values except this one. I have tried Session::put() as well as Session::flash() but did not work. The category list is retrieved once you chose section as it requests the category list from the controller through ajax. How can I get the old value in the category dropdown list after the page refreshed.
Here is my section selection dropdown:
<select class="form-control sectionchoose" name="section_id" id="section_id">
<option value="">Choose Section</option>
#foreach($sections as $section)
<option value="{{$section['id']}}" #if(old('section_id') == $section['id']) selected #endif>{{$section['name']}} </option>
#endforeach
</select>
My categorylist dropdown:
<label class="col-sm-6">Chose Category</label>
<div class="categorylist">
#include('admin.deal-management.categorylist')
</div>
And this is my categorylist view file:
<select class="form-control " name="category_id" id="category_id">
<option value="">Choose Category</option>
#foreach($categories as $category)
<option value="{{$category['id']}}" #if(old('category_id') == $category['id']) selected #endif>
{{$category['category_name']}}
</option>
#endforeach
</select>
and this is my main controller:
public function addEditDeals(DealAddEditRequest $request, $id=null){
//*** post starts here ***/
if($request->isMethod('post')){
$message = 'Updated successfully';
$data=$request->all();
$deal->fill($request->validated());
$deal->save();
return redirect()->back()->with($message);
}
This is my categorylist controller:
public function findCategories(Request $request){
if($request->json()){
$data = $request->all();
$categories = Category::where(['section_id' => $data['id'], 'status'=>1])->get()->toArray();
return view('admin.deal-management.categorylist',compact('categories'));
}
}
And finally, this is the jQuery part:
$(document).ready(function (){
let sectionid = $('.sectionchoose').val();
$.ajax({
headers: {
'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
datatype: 'json',
url : '/admin/selectsection',
data: {id:sectionid},
success: function(response){
$('.categorylist').html(response)
}, error:function(){
}
})
})
Finally, I was able to find the solution. Whoever has the same issue can use the approach below:
Step 1: Send the Session value through the with() command:
return redirect()->back()->withErrors($validator)
->withInput()->with('cat_id',$data['category_id']);
}
Step 2: Retreive the data in your main blade and attain hidden input:
<input class="cat_id" id="asd" type="hidden" value="{{Session::get('cat_id')}}"/>
Step 3: Get the retreived session value in Jquery:
$(document).ready(function (){
let sectionid = $('.sectionchoose').val();
let cat_id;
if($('#asd').val()){
cat_id = $('#asd').val();
} else {
cat_id = 0;
}
$.ajax({
headers: {
'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
datatype: 'json',
url : '/admin/selectsection',
data: {id:sectionid, cat_id:cat_id},
success: function(response){
$('.categorylist').html(response)
}, error:function(){
}
})
})
Step 4: Send the session value to your dependent blade again (as cat_id here)
public function findCategories(Request $request){
if($request->json()){
$data = $request->all();
$cat_id = $data['cat_id'] ?? '';
$categories = Category::where(['section_id' => $data['id'], 'status'=>1])->get()->toArray();
return view('admin.deal-management.categorylist',compact('categories','cat_id'));
}
}
Done! As far as I know, there is not any other way to get old value of dependent dropdown list value so far.

cascading dropdown not Working in Laravel 7

i am trying to use cascading dropdown list in mvc. main category is working but in subcategory having some problem.it doesn't show any value when i choose from main category
in Blade:
<div class="form-group">
<label for="cat_id">Category <span class="text-danger">*</span></label>
<select name="cat_id" id="cat_id" class="form-control">
<option value="">--Select any category--</option>
#foreach($categories as $key=>$cat_data)
<option value='{{$cat_data->id}}'>{{$cat_data->title}}</option>
#endforeach
</select>
</div>
<div class="form-group" id="child_cat_div">
<label for="child_cat_id">Sub Category</label>
<select name="child_cat_id" id="child_cat_id" class="form-control">
<option value="">--Select any category--</option>
</select>
</div>
#push('scripts')
<script>
$('#cat_id').on('change',function(e) {
var cat_id=$(this).val();
// alert(cat_id);
if(cat_id !=null){
// Ajax call
$.Ajax({
url:"/backend/category/"+cat_id,
data:{
_token:"{{csrf_token()}}",
id:cat_id
},
type:"POST",
success:function(response){
if(typeof(response) !='object'){
response=$.parseJSON(response)
}
// console.log(response);
var html_option="<option value=''>Select sub category</option>"
if(response.status){
var data=response.data;
// alert(data);
if(response.data){
$('#loader').css("visibility", "visible");
// $('#child_cat_div').removeClass('d-none');
$.each(data,function(id,title){
html_option +="<option value='"+ id +"'>" + title +"</option>"
});
}
else{
}
}
else{
$('#child_cat_div').addClass('d-none');
}
$('#child_cat_id').html(html_option);
}
});
}
else{
}
}) </script> #endpush
in Route:
Route::POST('/category/{id}','Admin\CategoryController#getChildByParent');
in article Controller:
public function create()
{
$categories=Category::where('is_parent',1)->get();
$photos = Photo::all();
$tags = Tag::all();
$articles = Article::all();
return view('backend.articles.create',
compact('categories','photos','tags','articles'));
}
in Category Controller:
public function getChildByParent(Request $request){
$category=Category::findOrFail($request->id);
$child_cat=Category::getChildByParentID($request->id);
return response()->json([$child_cat]);
return response()->json([
'child_cat' => $child_cat]);
}
in model category:
public static function getChildByParentID($id){
return Category::where('parent_id',$id)->orderBy('id','ASC')->pluck('title','id');
}

How to make dynamic dropdown for update form Laravel

I am interested in creating a dynamic dropdown on my form. For store.blade.php it's been successful. But for edit.blade.php, I don't know what to do. I can only set values ​​for the first dropdown column, while the second dropdown column, I can't.
Edit: How to display the values ​​for the idkelas column that have been stored in the Update Form?
Blade
Column1
<select name="idkamar" class="form-control">
<option value="">Pilih kamar</option>
#foreach ($kamar as $key=>$value)
<option value="{{ $key }}"{{ ( $listkamar->idkamar == $key ) ? ' selected' : '' }}>{{ $value }}</option>
#endforeach
</select>
Column2
<select name="idkelas" class="form-control"></select>
Javascript
<script type="text/javascript">
$(document).ready(function() {
$('select[name="idkamar"]').on('change', function() {
var kamarID = $(this).val();
if(kamarID) {
$.ajax({
url: '/kamar/ajax/'+kamarID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="idkelas"]').empty();
$.each(data, function(key, value) {
$('select[name="idkelas"]').append('<option value="'+ key +'">'+ value +'</option>');
});
}
});
}else{
$('select[name="idkelas"]').append('<option value="'+ key +'">'+ value +'</option>')
}
});
});
</script>
Controller
public function myformAjax($id)
{
$kelas = DB::table("kelas")
->where("idkamar",$id)
->pluck("name","id");
return json_encode($kelas);
}
public function edit($id)
{
$listkamar = ListKamar::find($id);
$kamar = DB::table("kamar")->pluck('name','id');
return view('listkamar.edit',compact('listkamar','kamar'));
}
You just need to pass $kelas in edit action. And in the view template, you will get all the values of that.

How to create drop down

I want to generate a list on items in a drop down based on a previous choice from another select. All items ar in the database.
Here is what I did:
Javascript:
$(document).ready(function () {
$(document).on('change', '#province_name', function() {
var province_id = $(this).val();
var div = $(this).parent();
var op = " ";
$.ajax({
type: 'get',
url: '{!!URL::to('admin/findIDProvince')!!}',
data: {'id':province_id},
success: function(data){
for (var i = 0; i < data.length; i++){
op += '<option value="'+data[i].id+'">'+data[i].city_name+'</option>';
}
div.find('#city').html(" ");
div.find('#city').append(op);
},
error: function(){
console.log('success');
},
});
});
});
Routes (web.php):
Route::namespace('Admin')->prefix('admin')->middleware('auth', 'CheckAdmin')->group(function (){
$this->get('/findIDProvince', 'SchoolsListController#findIDProvince');
});
Controller (Admin/SchoolsListController.php):
public function findIDProvince(Request $request)
{
$data = City::select('name', 'id')->where('province_id', $request->id)->take(100)->get();
return response()->json($data);
}
HTML (view.blade.php)
<div class="form-group">
<label class="col-md-3" for="province_name">province_name</label>
<div class="col-md-9">
<select id="province_name" name="province_name" class="form-control col-md-12" required>
#foreach($province_names as $province_name)
<option value="{{ $province_name->id }}">{{ $province_name->province_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3" for="city_name">city_name</label>
<div class="col-md-9">
<select id="city_name" name="city_name" class="form-control col-md-12" required>
</select>
</div>
</div>
What am I doing wrong?
First, create a hidden filed with the value for which the option that need to be selected.
<input type="hidden" value="{{ $yourOptionValueToSelect }}" id="selectThis">
Then with jQuery find the matching value from your option and change the corresponding attribute as selected.
$('option').each(function() {
if (this.value == $('#selectThis').val()) {
this.setAttribute('selected', 'selected');
}
});
Example:
<input type="hidden" value="2" id="selectThis">
<select>
<option value="1">Hello</option>
<option value="2">World</option>
</select>
Here Option 2 will be selected by default with the above jQuery Code.
In your view it will be changed to:
<option value="2" selected="selected">World</option>
// prepend : attach default value to the begining of the dropdown for region
// $('.region').prepend('<option value="default" selected="selected">Please select</option>');
$('.region').on('change', function(e) {
$('.select2-selection__placeholder').css("font-size", '11px'); // change the font size of the select box
var region = e.target.value;
$.ajax({
url: "{{ url('/dropdown/station?region')}}=" + region, // value.id refers to ring_id
type: "get",
cache: false,
beforeSend: function() {
$('.ajax-loader').css("visibility", "visible");
},
complete: function() {
$('.ajax-loader').css("visibility", "hidden");
},
dataType: 'json',
success: function(data) {
// empty the option before we populate the dropdown
$('#station').empty();
// define default value
$('#station').append('<option value="default" selected="selected" disabled hidden></option>');
$.each(data, function(index, subCatObj) {
// alert(subCatObj.substation_name);
$('#station').append($('<option>').text(index).attr('value', index));
$('#station').append('' + index + '');
});
},
error: function(error) {
console.log(error);
}
});
});
$('.station').on('change', function(e) {
var station = e.target.value;
$.ajax({
url: "{{ url('/dropdown/kv-station?station')}}=" + station, // value.id refers to ring_id
type: "get",
cache: false,
beforeSend: function() {
$('.ajax-loader').css("visibility", "visible");
},
complete: function() {
$('.ajax-loader').css("visibility", "hidden");
},
dataType: 'json',
success: function(data) {
// empty the option before we populate the dropdown
$('#kvStation').empty();
// define default value
$('#kvStation').append('<option value="default" selected="selected" disabled hidden></option>');
$.each(data, function(index, subCatObj) {
// alert(subCatObj.substation_name);
$('#kvStation').append($('<option>').text(index).attr('value', index));
$('#kvStation').append('' + index + '');
});
},
error: function(error) {
console.log(error);
}
});
});
// kv station dropdown event
$('.kvStation').on('change', function(e) {
var station = e.target.value;
$.ajax({
url: "{{ url('/dropdown/ring?station') }}=" + station, // value.id refers to ring_id
type: "get",
cache: false,
beforeSend: function() {
$('.ajax-loader').css("visibility", "visible");
},
complete: function() {
$('.ajax-loader').css("visibility", "hidden");
},
dataType: 'json',
success: function(data, jqXHR) {
// remove the previous data ferom select
$('#ring').empty();
// checking the status code; if 204: no content, then
if (jqXHR.status === 204) {
$('#ring').append('<option value="default" selected="selected">No data</option>');
} else {
$('#ring').append('<option value="default" selected="selected" disabled hidden></option>');
}
// empty the option before we populate the dropdown
$.each(data, function(index, subCatObj) {
$('#ring').append($('<option>').text(subCatObj).attr('value', index));
$('#ring').append('' + index + '');
});
},
error: function(error) {
console.log(error);
}
});
// ring dropdown event
$('.ring').on('change', function(e) {
var id = e.target.value;
window.open('{{url(' / ring ')}}/' + id, '_blank');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="bottom">
<ul>
<li>
<label>Region
<select id="region-select" class=" form-control select2 region" name="region">
<option></option>
#foreach($regions as $region)
<option value="{{$region->region}}">
{{$region->region}}
</option>
#endforeach
</select>
{{--        {!! Form::select('region', $regions,'Please select ...', ['class' => 'region form-control select2', 'id' => 'region-select']) !!}--}}
</label>
</li>
<li>
<label>Station
<select id="station" class=" selectpicker station form-control input-sm" name="station">
<option value=""></option>
</select>
</label>
</li>
<li>
<label>KV Station
<select id="kvStation" class="kvStation form-control input-sm" name="kv-station">
<option value=""></option>
</select>
</label>
</li>
<li>
<label>Ring
<select id="ring" class="ring form-control input-sm" name="ring">
<option value=""></option>
</select>
</label>
</li>
</ul>
<i id="loading-image" hidden class="livicon" data-name="spinner-three" data-size="50" data-c="#fff" data-hc="#fff" data-loop="true"></i>
<div class="ajax-loader">
<img id="loading-image" class="loading-image img-responsive" src="{{ asset('images/ajax-loader.gif') }}">
</div>
</div>

codeigniter dependent dropdown error

This is my code. It does not work with codeigniter 3.0 and jquery. I need to use dropdown dependent so I made that but it will be display "Error occur..." by alert() after choosing any item in first dropdown.
Please have a look to my source code. I don't know what is wrong. Thanks everyone
VIEW:
<script type="text/javascript">
$(document).ready(function(){
$('#senf').on('change', function(){
var senf_id = $(this).val();
if(senf_id == '')
{
$('#raste').prop('disabled', true);
}
else
{
$('#raste').prop('disabled', false);
$.ajax({
url:"<?php echo base_url() ?>index.php/shoppings/get_subgroup/",
type: "POST",
data: {'senf_id' : senf_id},
dataType: 'json',
success: function(data){
alert('okkk');
},
error: function(){
alert('Error occur...!!');
}
});
}
});
});
</script>
<div class="form-group ">
<label for="group_name" class="control-label col-lg-2">group 1</label>
<select id="senf" name="group">
<option value="" selected="selected">select</option>
<?php
foreach ($get_groups as $value) {
$group_id = $value['group_shop_id'];
$group_name = $value['group_shop_name'];
?>
<option value="<?php echo $group_id; ?>"> <?php echo $group_name; ?> </option>
<?php } ?>
</select>
<label for="raste" >group 2</label>
<select id="raste" name="raste">
<option value="">select</option>
</select>
</div>
CONTROLLER:
public function get_subgroup(){
$id = $this->input->post('senf_id');
$ajax_get_subgroup = $this->shopping_model->ajax_get_subgroup($id);
$pro_select_box = '';
$pro_select_box .= '<option value="">Select Province</option>';
foreach($ajax_get_subgroup as $ajax_get_subgroup_value){
$pro_select_box .= '<option>'. $ajax_get_subgroup_value->cat_shop_name .'</option>';
}
echo json_encode($pro_select_box);
}
MODEL:
public function ajax_get_subgroup($id){
$query = $this->db->get_where('cat_shopping_group', array('group_shop_id' => $id));
return $query->result();
}
try this
Controller
public function ajax_get_subgroup()
{
extract($_POST);
$tmp='';
$sql = "SELECT * FROM cat_shopping_group where group_shop_id=$id";
$data = $this->db->query($sql)->result_array();
$tmp .="<option value=''>-- Select --</option>";
foreach($data as $row)
{
$tmp .="<option value='".$row['your_id']."'>".$row['cat_shop_name ']."</option>";
}
die($tmp);
}`
AJAX
function get_data()
{
var id = $('#senf').val()
datana= 'id='+id
$.ajax({
type: 'POST',
url: '<?=base_url()?>your_controller/ajax_get_subgroup',
data: datana,
error: function(data) {
alert('Failed');
},
success: function(data)
{
$('#raste').html(data)
}
})
}
Views
<select id="senf" name="group" onchange='ajax_get_subgroup();'>
<option value="" selected="selected">select</option>
<?php
your code
?>
</select>
<select id="raste">
</select>
Hope this help.

Resources