Laravel - Dependent Drop Down Using Ajax
Resources\View\ index.blade.php:
<h1>Dependent Drop Down</h1>
<select name="country" id="country">
<option hidden>Select Country</option>
@foreach($country as $list)
<option value="{{$list->id}}">{{$list->country}}</option>
@endforeach
</select>
<select name="state" id="state">
<option hidden>Select State</option>
<option value=""></option>
</select>
<select name="city" id="city">
<option hidden>Select City</option>
<option value=""></option>
</select>
</body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
jQuery(document).ready(function() {
jQuery('#country').change(function() {
// jQuery('#city').html(result)
// alert('ss')
let country_id = jQuery(this).val();
jQuery('#city').html('<option hidden>Select City</option>')
// alert(country_id);
jQuery.ajax({
url: '/getstate',
type: 'post',
data: 'country_id=' + country_id + '&_token= {{csrf_token()}}',
success: function(result) {
jQuery('#state').html(result)
}
})
})
jQuery('#state').change(function() {
// alert('ss')
let state_id = jQuery(this).val();
// alert(state_id);
// return false;
jQuery.ajax({
url: '/getcity',
type: 'post',
data: 'state_id=' + state_id + '&_token= {{csrf_token()}}',
success: function(result) {
jQuery('#city').html(result)
}
})
})
})
</script>
routes\web.php:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\controllers\dropdown_controller;
Route::GET('/', [dropdown_controller::class, 'index']);
//-------------------------GET STATE-------------------------
Route::POST('/getstate', [dropdown_controller::class, 'getstate']);
//-------------------------GET CITY-------------------------
Route::POST('/getcity', [dropdown_controller::class, 'getcity']);
// Route::get('/', function () {
// return view('welcome');
// });
App\Http\controllers\dropdown_controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class dropdown_controller extends Controller
{
//
public function index(Request $request)
{
$data['country'] = DB::table('country')->get();
return view('index', $data);
}
public function getstate(Request $request)
{
$country_id = $request->post('country_id');
$state = DB::table('state')->where('country', $country_id)->get();
print_r($state);
$html = '<option hidden>Select State</option>';
foreach ($state as $list) {
$html .= '<option value="' . $list->id . '">' . $list->State . '</option>';
}
echo $html;
}
public function getcity(Request $request)
{
$state_id = $request->post('state_id');
$city = DB::table('city')->where('state', $state_id)->get();
$html = '<option hidden>Select city</option>';
foreach ($city as $list) {
$html .= '<option value="' . $list->id . '">' . $list->city . '</option>';
}
echo $html;
}
}
Comments
Post a Comment