DEPENDABLE DROPDOWN AJAX WITH AND WITHOUT AJAX [ XMLHttpRequest ]
LARAVEL AJAX DEPENDABLE DROPDOWN [ COUNTRY - STATE - CITY ]
CONTROLLER
PHP ARTISAN MAKE:CONTROLLER USERCONTROLLER
USERCONTROLLER.PHP
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Response;
use Redirect;
use App\Models\{Country, State, City};
class UserController extends Controller
{
//
public function index()
{
$data['countries'] = Country::get(["name", "id"]);
return view('index', $data);
}
public function fetchState(Request $request)
{
$data['states'] = State::where("country_id",$request->country_id)->get(["name", "id"]);
return response()->json($data);
}
public function fetchCity(Request $request)
{
$data['cities'] = City::where("state_id",$request->state_id)->get(["name", "id"]);
return response()->json($data);
}
public function home()
{
$data['countries'] = Country::get(["name", "id"]);
return view('home', $data);
}
public function getstate($id)
{
$data['states'] = State::where("country_id",$id)->get(["name", "id"]);
return response()->json($data);
}
public function getcity($id)
{
$data['cities'] = City::where("state_id",$id)->get(["name", "id"]);
return response()->json($data);
}
}
MAKE MIGRATION TABLE TO CREATE COUNTRY STATE & CITY
php artisan make:migration create_country_state_city_tables
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCountryStateCityTables extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('countries', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('sortname');
$table->string('phonecode');
$table->timestamps();
});
Schema::create('states', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('country_id');
$table->timestamps();
});
Schema::create('cities', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('state_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('countries');
Schema::drop('states');
Schema::drop('cities');
}
}
php artisan make:model Country
php artisan make:model State
php artisan make:model City
MAKE VIEW PAGES
WITH AJAX AND JQUERY :
INDEX.BLADE.PHP
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="content">
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel Dependent AJAX Dropdown Tutorial</title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
<div class="row justify-content-center">
<div class="col-md-5">
<h2 class="mb-4">Laravel AJAX Dependent Country State City Dropdown Example</h2>
<form>
<div class="form-group mb-3">
<select id="country-dd" class="form-control">
<option value="">Select Country</option>
@foreach ($countries as $data)
<option value="{{$data->id}}">
{{$data->name}}
</option>
@endforeach
</select>
</div>
<div class="form-group mb-3">
<select id="state-dd" class="form-control">
</select>
</div>
<div class="form-group">
<select id="city-dd" class="form-control">
</select>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#country-dd').on('change', function () {
var idCountry = this.value;
$("#state-dd").html('');
$.ajax({
url: "{{url('api/fetch-states')}}",
type: "POST",
data: {
country_id: idCountry,
_token: '{{csrf_token()}}'
},
dataType: 'json',
success: function (result) {
$('#state-dd').html('<option value="">Select State</option>');
$.each(result.states, function (key, value) {
$("#state-dd").append('<option value="' + value
.id + '">' + value.name + '</option>');
});
$('#city-dd').html('<option value="">Select City</option>');
}
});
});
$('#state-dd').on('change', function () {
var idState = this.value;
$("#city-dd").html('');
$.ajax({
url: "{{url('api/fetch-cities')}}",
type: "POST",
data: {
state_id: idState,
_token: '{{csrf_token()}}'
},
dataType: 'json',
success: function (res) {
$('#city-dd').html('<option value="">Select City</option>');
$.each(res.cities, function (key, value) {
$("#city-dd").append('<option value="' + value
.id + '">' + value.name + '</option>');
});
}
});
});
});
</script>
</body>
</html>
WITHOUT AJAX
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="content">
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel Dependent AJAX Dropdown Tutorial</title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
<div class="row justify-content-center">
<div class="col-md-5">
<h2 class="mb-4">Laravel XMLHttpRequest Dependent Country State City Dropdown Example</h2>
<form>
<div class="form-group mb-3">
<select id="country-dd" class="form-control" onchange="showHint(this.value)">
<option value="">Select Country</option>
@foreach ($countries as $data)
<option value="{{$data->id}}">
{{$data->name}}
</option>
@endforeach
</select>
</div>
<div class="form-group mb-3">
<select id="state-dd" class="form-control" onchange="showCity(this.value)">
</select>
</div>
<div class="form-group">
<select id="city-dd" class="form-control">
</select>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function showHint(str) {
console.log(str);
if (str.length == 0) {
document.getElementById("state-dd").innerHTML = "";
return;
}
const xhttp = new XMLHttpRequest();
xhttp.open("GET", "/getstate/"+str);
xhttp.responseType = 'json';
xhttp.onload = function(result) {
if (this.status == 200) {
// console.log('response', this.response); // JSON response
document.getElementById("state-dd").innerHTML ='<option value="">Select State</option>';
for (let i = 0; i < this.response.states.length; i++) {
document.getElementById("state-dd").innerHTML +=
'<option value="'+this.response.states[i].id+'">'+this.response.states[i].name+'</option>';
}
document.getElementById("city-dd").innerHTML ='<option value="">Select State</option>';
}
};
xhttp.send();
}
function showCity(str) {
console.log(str);
if (str.length == 0) {
document.getElementById("city-dd").innerHTML = "";
return;
}
const xhttp = new XMLHttpRequest();
xhttp.open("GET", "/getcity/"+str);
xhttp.responseType = 'json';
xhttp.onload = function(result) {
if (this.status == 200) {
// console.log('response', this.response); // JSON response
document.getElementById("city-dd").innerHTML ='<option value="">Select State</option>';
for (let i = 0; i < this.response.cities.length; i++) {
document.getElementById("city-dd").innerHTML +=
'<option value="'+this.response.cities[i].id+'">'+this.response.cities[i].name+'</option>';
}
}
};
xhttp.send();
}
</script>
</body>
</html>
ROUTES >> WEB.PHP
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
// WITH AJAX
Route::get('/',[UserController::class, 'index']);
Route::post('api/fetch-states', [UserController::class, 'fetchState']);
Route::post('api/fetch-cities', [UserController::class, 'fetchCity']);
// WITHOUT AJAX
Route::get('/home',[UserController::class, 'home']);
Route::get('/getstate/{id}',[UserController::class, 'getstate']);
Route::get('/getcity/{id}',[UserController::class, 'getcity']);
Comments
Post a Comment