Laravel How to append Ajax json in Select option - laravel

what is issue with my code, it returns empty drop down. i want drop down of nationality table, in teachers profile.
View:
<select class="form-control" name="nation_id" id="nation_id">
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id"
value="{{ #$teacher->nation_id}}">
</select>
ajax code which returns empty dropdown: Ajax:
<script>
$(document).ready(function($){
$.get('nations-list', function(data) {
let teacher_nation_id = $('#teacher_nation_id').val();
let nations = $('#nation_id');
nations.empty();
$.each(data, function(key, value) {
nations.append("<option value='"+ key +"'>" + value + "</option>");
});
nations.val(teacher_nation_id);
});
});
</script>
My Controller:
public function ajaxrequest(Request $request)
{
$nations = Nation::all()->pluck('nation', 'id');
return response()->json($nations);
}
Here is my route:
Route:
Route::get('nations-list','TeachersController#ajaxrequest');

Try this,
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id"
value="{{ #$teacher->nation_id}}">
<select class="form-control" name="nation_id" id="nation_id">
</select>
<select class="form-control" name="area" id="area">
</select>
Ajax code:
<script type="text/javascript">
$(document).ready(function($){
$('#nation_id').click(function($){
var tid = $('#teacher_nation_id').val();
if(tid){
$.ajax({
type:"get",
url:"{{url('/getNation)}}/"+tid,
success:function(res)
{
$('#nation_id').empty();
$("#nation_id").append('<option>--Select Nation--</option>');
if(res)
{
$.each(res,function(key,value){
$('#nation_id').append($("<option/>", {
value: key,
text: value
}));
});
}
}
});
}
});
$('#nation_id).change(function(){
var nid = $(this).val();
if(nid){
$.ajax({
type:"get",
url:"{{url('/getArea')}}/"+nid,
success:function(res)
{
$("#area").empty();
$("#area").append('<option>--Select Area--</option>');
if(res)
{
$.each(res,function(key,value){
$('#area').append($("<option/>", {
value: key,
text: value
}));
});
}
}
});
}
});
});
</script>
Controller:
public function getNation($id)
{
$nations= DB::table("nations")
->where("teacher_nation_id",$id)
->pluck("nation","id")
->toArray();
return response()->json($nations);
}
public function getArea($id)
{
$areas= DB::table("areas")
->where("nation_id",$id)
->pluck("area","id")
->toArray();
return response()->json($areas);
}
Route:
Route::get('/getNation/{id}','NationsController#getNation);
Route::get('/getArea/{id}','AriasController#getArea);
//Here I assumes that You have different controller named AreasController you can gave name of your controller
Hope it will useful for you..
Good Luck...

Related

Ajax how change value id to text database?

I have a problem that is the value displayed in the database is the id value not the value of the text that appears in the input label. then my question is how to change the id value to a text value?
route web.php
`Route::get('/selectProvinces', [App\Http\Controllers\Admin\ManagementController::class, 'provinces'])->name('province.index'); `
ajax script
<script>
$(document).ready(function () {
$("#selectProvinces").select2({
placeholder: 'Pilih Provinsi',
ajax: {
url: "{{route('province.index')}}",
processResults: function ({
data
}) {
return {
results: $.map(data, function (item) {
return {
id: item.id,
text: item.name
}
})
}
}
}
});
</script>
blade.php boostrap
<div class="row">
<label for="formGroupExampleInput2">Provinsi</label>
<div class="col">
<select id="selectProvinces" class="form-control selectpicker" name="provinces">
</select>
</div>
</div>
controller
public function management_create(Request $request) {
Member::create([
'provinces' => $request->provinces,
]);
Alert::success('Success', 'Member berhasil dibuat');
return redirect()->route('management');
}
i hope the value changes text value like "East Java" not the number

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 can I fetch autocomplete data into their respected element using Ajax and Laravel?

Here is my problem.
I'm trying to fetch the data from an auto-completing text-box.
There are two text-boxes:
Region and province.
I have successfully fetched the data on the text-box having region as name.
My problem is, it gives the same value to the next text-box having province as name.
In my Laravel blade I have this code:
<input id="region" type="text" class="form-control" name="region" value="" required autofocus>
<div id="regionList"> </div>
<input id="province" type="text" class="form-control" name="province" value="" required autofocus>
<div id="provinceList"> </div>
I have also a javascript file named auto-complete
$(document).ready(function() {
$('#region').keyup(function() {
var region = $(this).val();
if (region != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url: "register/showRegion",
method: "POST",
data: { region: region, _token: _token },
success: function(data)
{
$('#regionList').fadeIn();
$('#regionList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
$('#province').keyup(function() {
var province = $(this).val();
if (province != '')
{
var _prov_token = $('input[name="_token"]').val();
$.ajax({
url: "register/showProvince",
method: "POST",
data: { province: province, _token: _token },
success: function(data)
{
$('#provinceList').fadeIn();
$('#provinceList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
});
And on my routes I included this
Route::post('/register/showRegion', 'LocationController#showRegion');
Route::post('/register/showProvince', 'LocationController#showProvince');
And on my controller is this
public function index() {
return view('auth.register');
}
function showRegion(Request $request)
{
if ($request->get('region'))
{
$region = $request->get('region');
$regions = Refregion::where('regDesc', 'LIKE', "$region%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($regions as $region)
{
$output .= '<li>'.$region->regDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
function showProvince(Request $request)
{
if ($request->get('province'))
{
$province = $request->get('province');
$province = Refprovince::where('provDesc', 'LIKE', "province%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($provinces as $province)
{
$output .= '<li>'.$province->provDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
I'm trying to figure out why it gives the same value to the other text-box "province" when I have selected region.
Can someone help me with this, or at least explain to me why this happen?
Thank you
change it
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
on this
$('#regionList').on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
and change it
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
on this
$('#provinceList').on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});

ajax not return anything when checkbox is checked

I have a list of manufacturers with checkbox when i checkbox is checked ajax is called and hit the controller but not return anything
I am using laravel 5.1
#foreach($manufacturers as $leedsManufacturer) {{-- #foreach($leedManufacturers as $leedsManufacturer) --}}
<div class="post" id="post{{$leedsManufacturer['mfgg_id']}}">
<label class=" my-checkbox gry2" id="manufacturer">{{str_limit($leedsManufacturer['mfgg_name'], 300)}}
<input type="checkbox" class="manufacturer common_selector" name="manufacturer[]" value="{{$leedsManufacturer['mfgg_id']}}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<span class="checkmark"></span>
</label>
</div>
#endforeach
#endif
script
$(document).ready(function() {
filter_data();
function filter_data() {
var manufacturer = get_filter('manufacturer');
// var products = get_filter('products');
// var chps_approved = get_filter('chps_approved');
$.ajax({
url: "{{url('ajax1')}}",
method: 'POST',
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
data:{manufacturer:manufacturer} ,
success:function(data){
console.log(data);
}
});
// alert(manufacturers);
}
function get_filter(class_name) {
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
alert(filter);
// return filter
}
$('.common_selector').click(function(){
filter_data();
});
});
controller
public function ajax1(Request $request){
$data= $request->manufacturer;
return response()->json($data);
}
On checkbox select, it should return the ID so i can use it in controller. but $request->manufacturer show this on console.
try this lets see if you are getting the id from the form. i use javascript alert
$(document).ready(function() {
filter_data();
function filter_data() {
var manufacturer = get_filter('manufacturer');
alert(manufacturer);
// var products = get_filter('products');
// var chps_approved = get_filter('chps_approved');
$.ajax({
url: "{{url('ajax1')}}",
method: 'POST',
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
data:{manufacturer:manufacturer} ,
success:function(data){
console.log(data);
}
});
// alert(manufacturers);
}
function get_filter(class_name) {
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
alert(filter);
// return filter
}
$('.common_selector').click(function(){
filter_data();
});
});

Laravel 5 multi dynamic dropdown

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

Resources