Laravel Ajax dropdown example - ajax

can someone please share working example of laravel ajax dropdown. there are so many examples about dependable dropdown, but i want simple dropdown of only one column, i have two tables teacher and nation, when teacher profile is open i want dropdown of nationality using ajax.
i have done it without ajax, but i don't know how to do with ajax.
without ajax:
<select name="nation_id" class="custom-select" >
<option selected value=" ">Choose...</option>
#foreach($nations as $nations)
<option value="{{#$nation_id}}" {{#$teacher->nation_id== $nations->id ? 'selected' : ''}} >{{#$nations->nation}}</option>
#endforeach
Controller:
$nations = nation::all();

<select class="form-control" name="nation_id" id="nation_id">
<option value="">Select nation</option>
#foreach($nations as $nation)
<option value="{{ $nation->nation_id }}">{{ $nation->nation_name }} </option>
#endforeach
</select>
<select class="form-control" name="teacher" id="teacher">
</select>
now the ajax code:
<script type="text/javascript">
$('#nation_id).change(function(){
var nid = $(this).val();
if(nid){
$.ajax({
type:"get",
url:"{{url('/getTeacher)}}/"+nid,
success:function(res)
{
if(res)
{
$("#teacher").empty();
$("#state").append('<option>Select Teacher</option>');
$.each(res,function(key,value){
$("#teacher").append('<option value="'+key+'">'+value+'</option>');
});
}
}
});
}
});
</script>
now in controller file;
public function getTeacher($id)
{
$states = DB::table("teachers")
->where("nation_id",$id)
->pluck("teacher_name","teacher_id");
return response()->json($teachers);
}
And last for route file:
Route::get('/getTeacher/{id}','TeachersController#getTeacher');
Hope this will work..
Good Luck...

Create a route for your method which will fetch all the nations-
Route::get('nations-list', 'YourController#method');
Create a method in your controller for the above route-
public function method()
{
$nations = Nation::all()->pluck('nation', 'id');
return response()->json($nations)
}
Add a select box like this in your HTML-
<select id="nation_id" name="nation_id"></select>
If you want to auto select the option based on a variable then you can do this-
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id" value="{{ $teacher->nation_id ?? '' }}">
And then add this script in your HTML to fetch the nation list on page load-
<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); // This will select the default value
});
});
</script>

Related

Populate dynamic dropdown, Codeigniter

I'm trying to make a dynamic dropdown with Codeigniter but I'm having trouble getting the values on the next dropdown. When I select and option on the first dropdown, the second dropdown is not populated:
I'm also not familiar at using AJAX, I only write the script based on what I searched so please teach me what to do to make the dynamic dropdown work.
This is my Model:
public function category()
{
$this->db->order_by("category", "ASC");
$query = $this->db->get('categories');
return $query->result();
}
function get_subcategory($parent_id)
{
$this->db->where('parent_id', $parent_id);
$this->db->order_by('sub_category', 'ASC');
$query = $this->db->get('sub_categories');
$output = '<option value="">Select Sub-Category</option>';
foreach ($query->result() as $row) {
$output .= '<option value="' . $row['id'] . '">' . $row['sub_category'] . '</option>';
}
return $output;
}
My Controller:
public function category()
{
$data['title'] = 'List of Category';
$this->load->view('../admin/template/admin_header');
$this->load->view('../admin/template/admin_topnav');
$this->load->view('../admin/template/admin_sidebar');
$this->load->view('../admin/category/category', $data);
$this->load->view('../admin/template/admin_footer');
}
function get_subcategory()
{
if ($this->input->post('parent_id')) {
echo $this->Admin_model->get_subcategory($this->input->post('parent_id'));
}
}
View:
<div class="form-group">
<label for="" class="control-label">Category</label>
<select name="category" id="category" class="custom-select select2" required>
<option value="">- Select Category -</option>
<?php
foreach ($category as $row) {
echo '<option value="' . $row->id. '">' . $row->category . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="" class="control-label">Sub Category</label>
<select name="sub_category" id="sub_category_id" class="custom-select select2" required>
<option value="">- Select Sub Category -</option>
</select>
</div>
And script:
$(document).ready(function() {
$('#category').change(function() {
var parent_id = $('#category').val();
if (parent_id != '') {
$.ajax({
url: "<?php echo base_url(); ?>admin/get_subcategory",
method: "POST",
data: {parent_id:parent_id},
success: function(data) {
$('#sub_category_id').html(data);
}
});
} else {
$('#sub_category_id').html('<option value="">Select Sub Category</option>');
}
});
});
Your question doesn't mention it, but your CSS suggests your selects are actually using Select2. When you initialise a select as a Select2, it makes a copy of the initial HTML, and adds styling and JS to it, and it is the copy that you see and interact with. The original HTML is no longer visible or used at all.
So if you later come along and modify that original HTML, it will have no effect on the Select2 you already generated and can see an interact with on the page.
One solution is to reinitialise that Select2 after you modify it.
UPDATE
I've added a working snippet, with some hard-coded HTML to simulate what your AJAX returns. Click run to try it.
$(document).ready(function () {
// Initialise Select2s
$('.select2').select2();
// Fake HTML, simulate what your AJAX returns
let fakedHTMLResponse = '<option value="water">Water</option><option value="juice">Juice</option><option value="beer">Beer</option>';
$('#category').change(function () {
var parent_id = $('#category').val();
// console.log('parent_id', parent_id);
if (parent_id != '') {
// Your AJAX call happens here, let's simulate the success
// response it gets back, and handle it the same way.
$('#sub_category_id').select2('destroy')
.html(fakedHTMLResponse)
.select2();
} else {
$('#sub_category_id').html('<option value="">Select Sub Category</option>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<select id="category" class="select2" name="food">
<option value="">- Select Category -</option>
<option value="fruits">Fruits</option>
<option value="vegetables">Vegetables</option>
<option value="cakes">Cakes</option>
</select>
<select id="sub_category_id" class="select2" name="drink">
<option value="">- Select Sub Category -</option>
</select>
Note:
Convention is to use GET when retrieving data, and POST for changing data. Your AJAX calls are just retrieving data to display, so really should be GET;
If you are going to use a jQuery selector more than once, it makes sense to cache them. Eg in the above code you should do something like:
let $category = $('#category');
let $sub = $('#sub_category_id');
// And then every time you need to use that selectors, use the variable, eg:
$category.select2();
$category.change(function ...
$sub.select2('destroy');
// etc
In your success response write this and remove the else from down there.
success: function(data) {
$('#sub_category_id').append('<option value=>Select Sub Category</option>');
for (var i=0; i<data.length; i++) {
$('#sub_category_id').append($('<option>', {
value: data[i].id,
text : data[i].sub_category
}));
}
}
get AJAX response in the array from your controller and then run this through javascript like this.
id is id from your db
and sub_category is sub_category coming from your db
with ajax response array.

Getting value from (select2) to another filed input laravel

I have select2 field input. After using select2 its will showing new column and data from this input selected.
I have referenced like this link. So after I using select2, this value will show in a new column. But I don't know how to catch this data. I am using Laravel and this is my controller and view:
Controller
$collection = Alat::get(['nama_alat','no_inventaris','status_alat','id']);
foreach ($collection as $item) {
$inven[$item->id] = $item->no_inventaris.'-'.$item->nama_alat;
}
This is will shown in columns no_inventaris and nama_alat in the select2. But in the $collection, I have status_alat, this data is what I need to display in another column.
This is my view:
// This is form Select2
<div class="form-group">
<label>Pilih Inventaris</label>
<select class="form-control select2bs4" name="alat_id" id="alat_id" style="width: 100%;" aria-hidden="true" onchange="Show()">
<option value=""></option>
#foreach($inven as $id => $item )
<option value="{{ $id }}">{{ $item }} </option>
#endforeach
</select>
</div>
// This is form what i need to show another value
<div class="form-group" id="divid" style="display:none">
<label class="control-label" for="title">Kondisi Alat Sekarang:</label>
<input type="text" name="" class="form-control" id="value" data-error="Please enter title." readonly />
<div class="help-block with-errors"></div>
</div>
Here's my Javascript:
<script>
function Show()
{
var fieldValue = $('#alat_id').val();
if(fieldValue == "")
{
document.getElementById("divid").style.display = 'none';
}
else{
document.getElementById("divid").style.display = 'inline'
}
}
</script>
This data I need to catch in the controller $collection as status_alat. How can I catch this data after input the select2 and showing in the new column? This column is shown, but I don't know how to catch this data. Sorry for my bad English
The best solution should be using ajax, it is quite complicated to access a PHP collection variable inside a javascript. If it were me, I would create a function that fetch the selected select2 data by its id. This is my example code :
<script>
function select2Changed()
{
var alat_id = $('#alat_id').val();
if(fieldValue == ""){
document.getElementById("divid").style.display = 'none';
} else{
document.getElementById("divid").style.display = 'inline';
$.ajax({url: "[url]/get-alat-status/"+alat_id, success: function(result){
document.getElementById("value").value = result;
}});
}
}
</script>

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.

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

how to show content as default in ajax

I have ajax code that when I choose AREA (first select box) I get all the cities in this area.
The issue is when I first enter the page - I want that the second select box (the cities select box) to be fill with the area default (the first choice)
This is what I already have:
Client side:
<script>
$(document).ready(function(){
$('#areaID').change(function(){
var areaID=$('#areaID').val();
$('#cityID').load('scripts/ajax/getCities.php?areaID=' + areaID);
return false;
});
});
</script>
<form method="post" action="page.php">
<select id="first" name="areaID">
<option value="1">center</option>
<option value="2">north</option>
<option value="3">south</option>
</select>
<select id="cityID" name="cityID"> </select>
</form>
$(function () {
function updateCitySelectBox() {
var areaID = $('#areaID').val();
$('#cityID').load('scripts/ajax/getCities.php?areaID=' + areaID);
return false;
}
updateCitySelectBox();
$('#areaID').change(updateCitySelectBox);
});

Resources