Is your AJAX request triggered?
Dec 5, 2016
10
Level 1
Dropdown dependent
I am building a application where the user will select districts and then choose the villages.
after user selecting a distric, village list displayed ! My problem is a list of villages can not be displayed
maybe I wrong in ajax, If anyones find the solution, I hope will help to get the solution.
images : http://www.awesomescreenshot.com/image/1921416/042bfba084ddde31895f806c19427e13
this my view :
<div class="col-lg-4" >
{!!Form::open(array('url'=>'', 'files'=>true))!!}
<div class="form-group">
<label for="title">Pilih Kecamatan :</label>
<select class="form-control input-sm" name="kecamatan_id" id="districs">
@foreach ($kecamatan as $row)
<option value=""{{$row->id}}>{{$row->nama}}</option>
@endforeach
</select>
</div>
<div class="form-group">
<label for="">Pilih Kelurahan</label>
<select class="form-control input-sm" name="kelurahan_id" id="villages">
<option value=""></option>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default"> Pilih
</button>
</div>
{!! Form::close() !!}
</div>
ajax :
<script>
$('#districs').on('change', function(e){
$('#villages').find('option').remove().end();
var kec_id = $('#districs option:select').attr('value');
var info=$.get("{{url('ajax')}}",{kec_id:kec_id});
info.done(function(data){
$each(data,function(index,vilObj){
$('#villages').append('<option value="' +vilObj.id+'">'+vilObj.name+'</option>');
});
});
info.fail(function){
alert('ok');
});
});
</script>
myRoute:
Route::get('/', function () {
$kecamatan = App\Districs::all();
return view('welcome')->with('kecamatan',$kecamatan);
});
Route::auth();
Route::get('/home', 'HomeController@index');
Route::get('ajax', function(Request $request){
$kec_id = $request::Input(['kec_id']);
$villages = \App\Villages::where('kecamatan_id', '=', $kec_id)->get();
return Response::json($villages);
});
districs model :
protected $table = 'kecamatan';
protected $fillable = ['nama'];
public function villages()
{
return $this->hasMany('App\Villages');
}
villages model :
protected $table = 'kelurahan';
protected$fillable = ['nama','kecamatan_id'];
public function districs()
{
return $this->belongsTo('App\Districs');
}
Migration :
Schema::create('kecamatan', function (Blueprint $table) {
$table->increments('id');
$table->string('nama');
$table->timestamps();
});
Schema::create('kelurahan', function (Blueprint $table) {
$table->increments('id');
$table->string('nama');
$table->integer('kecamatan_id')->unsigned();
$table->timestamps();
$table->foreign('kecamatan_id')->references('id')->on('kecamatan');
});
end this my problem : http://www.awesomescreenshot.com/image/1921437/ff6f3fd33528f87ee148bbd41c4a4265
Please or to participate in this conversation.