Get the data with AJAX and display the results inside the select field.
Jun 6, 2022
4
Level 2
Parent and child category showing with Javascript
I have a checkout page where user will select his location. I stored all the states and areas in the database with parent_id. If customer select any state, the areas within this state should appear with javascript.
My State Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class State extends Model
{
protected $primaryKey = 'id';
protected $fillable = ['name', 'prefix', 'id', 'parent_id'];
public function children()
{
return $this->hasMany(State::class, 'parent_id', 'id');
}
}
My Controller:
public function index()
{
$states = State::where('publish', true)->where('parent_id', null)->get();
return view('checkout')->with([
'states' => $states
]);
}
My Blade View:
<select class="select_option" name="state" id="state" value="{{old('state')}}">
<option value="{{old('state')}}" {{auth()->user()->state == "" ? 'selected':''}}>Select State: </option>
@foreach($states as $state)
<option value="{{ old('state') ?? $state->name}}" name="{{$state->name}}" {{old('state', auth()->user()->state)==$state->name ? 'selected':''}}> {{$state->name}} </option>
@endforeach
</select>
//This part should appear when State Selected:
<select class="form-control select2 select2-hidden-accessible" name="area_id[]" multiple>
@foreach($state->children as $state)
<option class="form-control" value="{{$state->id}}" > {{$state->name}} </option>
@endforeach
</select>
Level 12
jQuery
$("#select_state_select_element").on('change', function() {
state_id = $(this).val();
$.ajax({
url : 'URL ENDPOINT',
type : 'GET/POST',
data : {
'state_id' : state_id
},
success : function(data) {
console.log(data);
},
});
}
Your URL endpoint must return the results for the selected area.
Please or to participate in this conversation.