This question is an exact duplicate of:
- without select category not show subcategory 2 answers
This is my create.blade.php file which include ajax function API and HTML tag code..
@extends('layouts.app')
@section('content')
<link rel="stylesheet" href="http://www.codermen.com/css/bootstrap.min.css">
<script src="http://www.codermen.com/js/jquery.js"></script>
<form enctype="multipart/form-data" method="post" action="{{route('post.store')}}" >
@csrf
<div class="form-group col-md-8">
Category<select name="category" id="category" class="form-control">
<option>select</option>
@foreach($categories as $category)
<option value="{{$category->id}}">{{$category->category}}</option>
@endforeach
</select>
</div>
<div class="form-group col-md-8">
Category<select name="subcategory" id="subcategory" class="form-control">
<option>select</option>
@foreach($subcategories as $subcategory)
<option value="{{$subcategory->id}}">{{$subcategory->subcategory}}</option>
@endforeach
</select>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function(){
var categoryID = $(this).val();
if(categoryID){
$.ajax({
type:"GET",
url:"{{url('/api/getSubcategory/')}}/"+categoryID,
success:function(res){
if(res){
$("#subcategory").empty();
$("#subcategory").append('<option>Select</option>');
$.each(res,function(key,value){
$("#category").append("<option value='"+key+"'>"+value+"</option>");
});
}else{
$("#subcategory").empty();
}
}
});
}else{
$("#subcategory").empty();
}
});
</script>
@endsection
This is my controller code which include create function and getSubcategory function
public function create(){
$categories = Category::all();
$subcategories = Subcategory::all();
return view('post.create', compact('categories', 'subcategories'));
}
public function getSubcategory(Request $request){
$id = $request->id;
$subcategories = Subcategory::where('category_id',$id)->select
('Subcategory','id')->get();
{{ dd(json_decode($subcategories, true)); }}
// return view('post.create')->with('subcategories', json_decode($subcategories, true));
}
This is my web.php
Route::get('/post/create', 'PostController@create')->name('post.create');
Route::get('api/getSubcategory/{id}', 'PostController@getSubcategory' );
Now my problem is API have data and give me
but when i open this page and select category still not show related subcategory