1659711000
Với trình đơn thả xuống Tự động điền, người dùng bị hạn chế chọn một tùy chọn từ trình đơn thả xuống theo từng bước. Dựa trên lựa chọn thả xuống, menu thả xuống tiếp theo là tự động điền với các tùy chọn.
Một ví dụ phổ biến về điều này là quốc gia, tiểu bang và thành phố thả xuống trên một biểu mẫu.
Để tải dữ liệu mà không cần làm mới trang cần sử dụng jQuery AJAX.
Trong hướng dẫn này, tôi chỉ cho bạn cách bạn có thể tự động điền vào menu thả xuống với PDO và PHP.
Tôi đang sử dụng 3 bảng trong ví dụ -
bảng quốc gia (Cửa hàng quốc gia) -
CREATE TABLE `countries` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
bảng trạng thái (Lưu trữ trạng thái của các quốc gia) -
CREATE TABLE `states` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(80) NOT NULL,
`country` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
bảng thành phố (Lưu trữ thành phố của các tiểu bang) -
CREATE TABLE `cities` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(80) NOT NULL,
`state` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Tạo config.php
kết nối cơ sở dữ liệu.
Mã đã hoàn thành
<?php
$server = "localhost";
$username = "root";
$password = "";
$dbname = "tutorial";
// Create connection
try{
$conn = new PDO("mysql:host=$server;dbname=$dbname","$username","$password");
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die('Unable to connect with the database');
}
Tạo 3 <select>
phần tử.
Điền <select >
phần tử đầu tiên với danh sách quốc gia và đặt trống 2 <select >
phần tử còn lại.
Thứ hai <select >
được điền tên tiểu bang dựa trên lựa chọn quốc gia từ <select >
phần tử thứ nhất bằng cách sử dụng jQuery AJAX.
Tương tự, thứ 3 <select >
được điền tên thành phố dựa trên lựa chọn tiểu bang từ <select>
phần tử thứ 2 bằng cách sử dụng jQuery AJAX.
Mã đã hoàn thành
<?php include "config.php"; ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table>
<tr>
<td>Country</td>
<td>
<!-- Country dropdown -->
<select id='sel_country' >
<option value='0' >Select Country</option>
<?php
## Fetch countries
$stmt = $conn->prepare("SELECT * FROM countries ORDER BY name");
$stmt->execute();
$countriesList = $stmt->fetchAll();
foreach($countriesList as $country){
echo "<option value='".$country['id']."'>".$country['name']."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>State</td>
<td>
<select id='sel_state' >
<option value='0' >Select State</option>
</select>
</td>
</tr>
<tr>
<td>City</td>
<td>
<select id='sel_city' >
<option value='0' >Select City</option>
</select>
</td>
</tr>
</table>
Xác định change
sự kiện trên <select id='sel_country'>
và <select id='sel_state'>
.
Lựa chọn quốc gia -
'ajaxfile.php'
và chuyển { request: 1, countryid: countryid }
như data
.Trên AJAX vòng lặp gọi lại thành công trên phản hồi JSON và thêm danh sách trạng thái bằng cách sử dụng <option >
trong <select id='sel_state'>
phần tử.
Lựa chọn tiểu bang -
'ajaxfile.php'
và chuyển { request: 2, stateid: stateid }
bằng địa chỉ data
.Trên vòng gọi lại thành công AJAX trên phản hồi JSON và nối thêm danh sách các thành phố bằng cách sử dụng <option >
trong <select id='sel_city'>
phần tử.
Mã đã hoàn thành
$(document).ready(function(){
// Country
$('#sel_country').change(function(){
var countryid = $(this).val();
// Empty state and city dropdown
$('#sel_state').find('option').not(':first').remove();
$('#sel_city').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 1, countryid: countryid},
dataType: 'json',
success: function(response){
var len = response.length;
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#sel_state").append("<option value='"+id+"'>"+name+"</option>");
}
}
});
});
// State
$('#sel_state').change(function(){
var stateid = $(this).val();
// Empty city dropdown
$('#sel_city').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 2, stateid: stateid},
dataType: 'json',
success: function(response){
var len = response.length;
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#sel_city").append("<option value='"+id+"'>"+name+"</option>");
}
}
});
});
});
Tạo một ajaxfile.php
tệp.
Xử lý 2 yêu cầu -
countryid
. Tìm nạp bản ghi từ states
bảng dựa trên id quốc gia.Lặp lại các bản ghi đã tìm nạp và khởi tạo $response
Mảng với một mảng kết hợp có id
và name
các khóa.
Trả về $response
Mảng ở định dạng JSON.
stateid
. Tìm nạp các bản ghi từ cities
bảng dựa trên id trạng thái.Lặp lại các bản ghi đã tìm nạp và khởi tạo $response
Mảng với một mảng kết hợp có id
và name
các khóa.
Trả về $response
Mảng ở định dạng JSON.
Mã đã hoàn thành
<?php
include "config.php";
$request = 0;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Fetch state list by countryid
if($request == 1){
$countryid = $_POST['countryid'];
$stmt = $conn->prepare("SELECT * FROM states WHERE country=:country ORDER BY name");
$stmt->bindValue(':country', (int)$countryid, PDO::PARAM_INT);
$stmt->execute();
$statesList = $stmt->fetchAll();
$response = array();
foreach($statesList as $state){
$response[] = array(
"id" => $state['id'],
"name" => $state['name']
);
}
echo json_encode($response);
exit;
}
// Fetch city list by stateid
if($request == 2){
$stateid = $_POST['stateid'];
$stmt = $conn->prepare("SELECT * FROM cities WHERE state=:state ORDER BY name");
$stmt->bindValue(':state', (int)$stateid, PDO::PARAM_INT);
$stmt->execute();
$statesList = $stmt->fetchAll();
$response = array();
foreach($statesList as $state){
$response[] = array(
"id" => $state['id'],
"name" => $state['name']
);
}
echo json_encode($response);
exit;
}
Bạn cần liên kết change
sự kiện trên menu thả xuống mà bạn muốn tự động điền vào một menu thả xuống khác.
Trong ví dụ này, tôi tự động điền 2 danh sách thả xuống nhưng bạn có thể tự động điền một hoặc nhiều danh sách thả xuống tương tự nếu bạn có trên một trang.
Nguồn: https://makitweb.com
1659711000
Với trình đơn thả xuống Tự động điền, người dùng bị hạn chế chọn một tùy chọn từ trình đơn thả xuống theo từng bước. Dựa trên lựa chọn thả xuống, menu thả xuống tiếp theo là tự động điền với các tùy chọn.
Một ví dụ phổ biến về điều này là quốc gia, tiểu bang và thành phố thả xuống trên một biểu mẫu.
Để tải dữ liệu mà không cần làm mới trang cần sử dụng jQuery AJAX.
Trong hướng dẫn này, tôi chỉ cho bạn cách bạn có thể tự động điền vào menu thả xuống với PDO và PHP.
Tôi đang sử dụng 3 bảng trong ví dụ -
bảng quốc gia (Cửa hàng quốc gia) -
CREATE TABLE `countries` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
bảng trạng thái (Lưu trữ trạng thái của các quốc gia) -
CREATE TABLE `states` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(80) NOT NULL,
`country` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
bảng thành phố (Lưu trữ thành phố của các tiểu bang) -
CREATE TABLE `cities` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(80) NOT NULL,
`state` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Tạo config.php
kết nối cơ sở dữ liệu.
Mã đã hoàn thành
<?php
$server = "localhost";
$username = "root";
$password = "";
$dbname = "tutorial";
// Create connection
try{
$conn = new PDO("mysql:host=$server;dbname=$dbname","$username","$password");
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die('Unable to connect with the database');
}
Tạo 3 <select>
phần tử.
Điền <select >
phần tử đầu tiên với danh sách quốc gia và đặt trống 2 <select >
phần tử còn lại.
Thứ hai <select >
được điền tên tiểu bang dựa trên lựa chọn quốc gia từ <select >
phần tử thứ nhất bằng cách sử dụng jQuery AJAX.
Tương tự, thứ 3 <select >
được điền tên thành phố dựa trên lựa chọn tiểu bang từ <select>
phần tử thứ 2 bằng cách sử dụng jQuery AJAX.
Mã đã hoàn thành
<?php include "config.php"; ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table>
<tr>
<td>Country</td>
<td>
<!-- Country dropdown -->
<select id='sel_country' >
<option value='0' >Select Country</option>
<?php
## Fetch countries
$stmt = $conn->prepare("SELECT * FROM countries ORDER BY name");
$stmt->execute();
$countriesList = $stmt->fetchAll();
foreach($countriesList as $country){
echo "<option value='".$country['id']."'>".$country['name']."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>State</td>
<td>
<select id='sel_state' >
<option value='0' >Select State</option>
</select>
</td>
</tr>
<tr>
<td>City</td>
<td>
<select id='sel_city' >
<option value='0' >Select City</option>
</select>
</td>
</tr>
</table>
Xác định change
sự kiện trên <select id='sel_country'>
và <select id='sel_state'>
.
Lựa chọn quốc gia -
'ajaxfile.php'
và chuyển { request: 1, countryid: countryid }
như data
.Trên AJAX vòng lặp gọi lại thành công trên phản hồi JSON và thêm danh sách trạng thái bằng cách sử dụng <option >
trong <select id='sel_state'>
phần tử.
Lựa chọn tiểu bang -
'ajaxfile.php'
và chuyển { request: 2, stateid: stateid }
bằng địa chỉ data
.Trên vòng gọi lại thành công AJAX trên phản hồi JSON và nối thêm danh sách các thành phố bằng cách sử dụng <option >
trong <select id='sel_city'>
phần tử.
Mã đã hoàn thành
$(document).ready(function(){
// Country
$('#sel_country').change(function(){
var countryid = $(this).val();
// Empty state and city dropdown
$('#sel_state').find('option').not(':first').remove();
$('#sel_city').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 1, countryid: countryid},
dataType: 'json',
success: function(response){
var len = response.length;
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#sel_state").append("<option value='"+id+"'>"+name+"</option>");
}
}
});
});
// State
$('#sel_state').change(function(){
var stateid = $(this).val();
// Empty city dropdown
$('#sel_city').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 2, stateid: stateid},
dataType: 'json',
success: function(response){
var len = response.length;
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#sel_city").append("<option value='"+id+"'>"+name+"</option>");
}
}
});
});
});
Tạo một ajaxfile.php
tệp.
Xử lý 2 yêu cầu -
countryid
. Tìm nạp bản ghi từ states
bảng dựa trên id quốc gia.Lặp lại các bản ghi đã tìm nạp và khởi tạo $response
Mảng với một mảng kết hợp có id
và name
các khóa.
Trả về $response
Mảng ở định dạng JSON.
stateid
. Tìm nạp các bản ghi từ cities
bảng dựa trên id trạng thái.Lặp lại các bản ghi đã tìm nạp và khởi tạo $response
Mảng với một mảng kết hợp có id
và name
các khóa.
Trả về $response
Mảng ở định dạng JSON.
Mã đã hoàn thành
<?php
include "config.php";
$request = 0;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Fetch state list by countryid
if($request == 1){
$countryid = $_POST['countryid'];
$stmt = $conn->prepare("SELECT * FROM states WHERE country=:country ORDER BY name");
$stmt->bindValue(':country', (int)$countryid, PDO::PARAM_INT);
$stmt->execute();
$statesList = $stmt->fetchAll();
$response = array();
foreach($statesList as $state){
$response[] = array(
"id" => $state['id'],
"name" => $state['name']
);
}
echo json_encode($response);
exit;
}
// Fetch city list by stateid
if($request == 2){
$stateid = $_POST['stateid'];
$stmt = $conn->prepare("SELECT * FROM cities WHERE state=:state ORDER BY name");
$stmt->bindValue(':state', (int)$stateid, PDO::PARAM_INT);
$stmt->execute();
$statesList = $stmt->fetchAll();
$response = array();
foreach($statesList as $state){
$response[] = array(
"id" => $state['id'],
"name" => $state['name']
);
}
echo json_encode($response);
exit;
}
Bạn cần liên kết change
sự kiện trên menu thả xuống mà bạn muốn tự động điền vào một menu thả xuống khác.
Trong ví dụ này, tôi tự động điền 2 danh sách thả xuống nhưng bạn có thể tự động điền một hoặc nhiều danh sách thả xuống tương tự nếu bạn có trên một trang.
Nguồn: https://makitweb.com
1658029140
Trình đơn thả xuống phụ thuộc động hạn chế lựa chọn của người dùng dựa trên lựa chọn thả xuống trước đó.
Trong hướng dẫn này, tôi chỉ cho bạn cách bạn có thể tự động điền vào danh sách thả xuống với dữ liệu cơ sở dữ liệu MySQL bằng JavaScript và PHP.
Tôi đang sử dụng 3 bảng trong ví dụ -
bảng quốc gia (Lưu trữ hồ sơ quốc gia) -
CREATE TABLE countries (
id serial PRIMARY KEY,
name varchar(80) NOT NULL
)
bảng trạng thái (Lưu trữ trạng thái của các quốc gia) -
CREATE TABLE states (
id serial PRIMARY KEY,
name varchar(80) NOT NULL,
country_id bigint NOT NULL
)
bảng thành phố (Lưu trữ thành phố của các tiểu bang) -
CREATE TABLE cities (
id serial PRIMARY KEY,
name varchar(80) NOT NULL,
state_id bigint NOT NULL
)
Tạo một config.php
tệp mới.
Mã đã hoàn thành
<?php
$host = "localhost"; /* Host name */$user = "root"; /* User */$password = "root"; /* Password */$dbname = "tutorial"; /* Database name */
// Create connection
$con = new mysqli($host, $user, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
Tìm nạp tất cả các bản ghi từ countries
bảng và tạo 3 <select>
phần tử -
<select >
là hiển thị đã tìm nạp countries
.Mã đã hoàn thành
<?php
include "config.php";
// Fetch countries
$sql = "SELECT * from countries order by name";
$stmt = $con->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
?>
<table>
<tr>
<td>Country</td>
<td>
<select id="country" onchange="getStates(this.value);">
<option value="0" >– Select Country –</option>
<?php
while ($row = $result->fetch_assoc() ){
$id = $row['id'];
$name = $row['name'];
echo "<option value='".$id."' >".$name."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>State</td>
<td>
<select id="state" onchange="getCities(this.value);" >
<option value="0" >– Select State –</option>
</select>
</td>
</tr>
<tr>
<td>City</td>
<td>
<select id="city" >
<option value="0" >– Select City –</option>
</select>
</td>
</tr>
</table>
Tạo ajaxfile.php
tệp.
Xử lý 2 yêu cầu AJAX -
states
bảng theo $country_id
giá trị và gán cho $result
. Lặp lại $result
và khởi tạo $data
Mảng với id
và name
các phím.Quay lại $data
ở định dạng JSON.
cities
bảng theo $state_id
giá trị và gán cho $result
. Lặp lại $result
và khởi tạo $data
Mảng với id
và name
các phím.Quay lại $data
ở định dạng JSON.
Mã đã hoàn thành
<?php
include 'config.php';
// Read POST data
$postData = json_decode(file_get_contents("php://input"));
$request = "";
if(isset($postData->request)){
$request = $postData->request;
}
// Get states
if($request == 'getStates'){
$country_id = 0;
$result = array();$data = array();
if(isset($postData->country_id)){
$country_id = $postData->country_id;
$sql = "SELECT * from states WHERE country_id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param("i", $country_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()){
$id = $row['id'];
$name = $row['name'];
$data[] = array(
"id" => $id,
"name" => $name
);
}
}
echo json_encode($data);
die;
}
// Get cities
if($request == 'getCities'){
$state_id = 0;
$result = array();$data = array();
if(isset($postData->state_id)){
$state_id = $postData->state_id;
$sql = "SELECT * from cities WHERE state_id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param("i", $state_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()){
$id = $row['id'];
$name = $row['name'];
$data[] = array(
"id" => $id,
"name" => $name
);
}
}
echo json_encode($data);
die;
}
Tạo 2 chức năng -
Trạng thái trống và thành phố thả xuống. Gửi yêu cầu AJAX POST tới ajaxfile.php
, chuyển {request: 'getStates', country_id: country_id}
dưới dạng data
và đặt dataType: 'json'
.
Trên vòng gọi lại thành công, bật response
và thêm <option >
vào trạng thái thả xuống.
Làm trống #city
menu thả xuống và gửi yêu cầu AJAX POST tới ajaxfile.php
, chuyển {request: 'getCities', state_id: state_id}
dưới dạng data
và đặt dataType: 'json'
.
Trên vòng gọi lại thành công, bật response
và thêm <option >
vào danh sách thả xuống của thành phố.
Mã đã hoàn thành
function getStates(country_id){
// Empty the dropdown
var stateel = document.getElementById('state');
var cityel = document.getElementById('city');
stateel.innerHTML = "";
cityel.innerHTML = "";
var stateopt = document.createElement('option');
stateopt.value = 0;
stateopt.innerHTML = '-- Select State --';
stateel.appendChild(stateopt);
var cityopt = document.createElement('option');
cityopt.value = 0;
cityopt.innerHTML = '-- Select City --';
cityel.appendChild(cityopt);
// AJAX request
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "ajaxfile.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = JSON.parse(this.responseText);
var len = 0;
if(response != null){
len = response.length;
}
if(len > 0){
// Read data and create <option >
for(var i=0; i<len; i++){
var id = response[i].id;
var name = response[i].name;
// Add option to state dropdown
var opt = document.createElement('option');
opt.value = id;
opt.innerHTML = name;
stateel.appendChild(opt);
}
}
}
};
var data = {request:'getStates',country_id: country_id};
xhttp.send(JSON.stringify(data));
}
function getCities(state_id){
// Empty the dropdown
var cityel = document.getElementById('city');
cityel.innerHTML = "";
var cityopt = document.createElement('option');
cityopt.value = 0;
cityopt.innerHTML = '-- Select City --';
cityel.appendChild(cityopt);
// AJAX request
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "ajaxfile.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = JSON.parse(this.responseText);
var len = 0;
if(response != null){
len = response.length;
}
if(len > 0){
// Read data and create <option >
for(var i=0; i<len; i++){
var id = response[i].id;
var name = response[i].name;
// Add option to city dropdown
var opt = document.createElement('option');
opt.value = id;
opt.innerHTML = name;
cityel.appendChild(opt);
}
}
}
};
var data = {request:'getCities',state_id: state_id};
xhttp.send(JSON.stringify(data));
}
Thực hiện theo các bước tương tự để tự động điền nhiều danh sách thả xuống.
Nếu dữ liệu không xuất hiện trên menu thả xuống khi bạn chọn một quốc gia hoặc một tiểu bang thì hãy sử dụng tab mạng của trình duyệt để gỡ lỗi. Kiểm tra lại các truy vấn SQL và giá trị POST.
Nguồn: https://makitweb.com
1658624640
Với trình đơn thả xuống tự động điền, người dùng bị hạn chế chọn một tùy chọn từ các tùy chọn có sẵn dựa trên lựa chọn của lựa chọn trước đó.
Trong hướng dẫn này, tôi chỉ cho bạn cách bạn có thể tự động điền vào danh sách thả xuống với dữ liệu cơ sở dữ liệu MySQL bằng cách sử dụng jQuery AJAX trong Laravel 8.
Mở .env
tệp.
Chỉ định máy chủ, tên cơ sở dữ liệu, tên người dùng và mật khẩu.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=
departments
và employees
lập bảng bằng cách sử dụng di chuyển và thêm một số bản ghi.php artisan make:migration create_departments_table
php artisan make:migration create_employees_table
database/migrations/
thư mục từ thư mục gốc của dự án.create_departments_table
và mở nó.up()
phương thức.public function up()
{
Schema::create('departments', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
create_employees_table
và mở nó.up()
phương thức.public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('username');
$table->string('name');
$table->string('email');
$table->integer('department');
$table->timestamps();
});
}
php artisan migrate
Tạo 2 mô hình -
Phòng ban -
php artisan make:model Departments
$fillable
tính.Mã đã hoàn thành
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Departments extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
}
Người lao động -
php artisan make:model Employees
$fillable
tính.Mã đã hoàn thành
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employees extends Model
{
use HasFactory;
protected $fillable = [
'username','name','email','department'
];
}
Tạo DepartmentsController
bộ điều khiển.
php artisan make:controller DepartmentsController
Tạo 2 phương thức -
departments
bảng và gán cho $departments['data']
.Tải index
chế độ xem và vượt qua $departments
.
Tìm nạp các bản ghi từ employees
bảng ở đâu department = $departmentid
và gán cho $empData['data']
.
Quay lại $empData
ở định dạng JSON.
Mã đã hoàn thành
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Departments;
use App\Models\Employees;
class DepartmentsController extends Controller {
public function index(){
// Fetch departments
$departments['data'] = Departments::orderby("name","asc")
->select('id','name')
->get();
// Load index view
return view('index')->with("departments",$departments);
}
// Fetch records
public function getEmployees($departmentid=0){
// Fetch Employees by Departmentid
$empData['data'] = Employees::orderby("name","asc")
->select('id','name')
->where('department',$departmentid)
->get();
return response()->json($empData);
}
}
routes/web.php
tệp.<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DepartmentsController;
Route::get('/', [DepartmentsController::class, 'index']);
Route::get('/getEmployees/{id}', [DepartmentsController::class, 'getEmployees']);
Tạo một index.blade.php
tệp mới trong resources/views/
thư mục.
HTML -
Tạo hai <select >
phần tử -
<select >
dành cho các phòng ban. Vòng lặp trên $departments['data']
để thêm <option>
.<select >
là dành cho nhân viên. Dữ liệu được tải trong menu thả xuống này dựa trên lựa chọn bộ phận bằng cách sử dụng jQuery AJAX.jQuery -
Xác định change
sự kiện trên menu thả xuống đầu tiên.
Đọc giá trị đã chọn và gán cho id
biến. Làm trống menu thả xuống thứ hai ngoại trừ menu đầu tiên <option>
.
Gửi yêu cầu AJAX GET tới 'getEmployees/'
và cũng chuyển id
giá trị, đặt dataType: 'json'
.
Khi thời lượng kiểm tra gọi lại thành công response
. Nếu độ dài lớn hơn 0 thì vòng lặp trên response
.
Tạo các tùy chọn và thêm vào #sel_emp
.
Mã đã hoàn thành
<!DOCTYPE html>
<html>
<head>
<title>Auto populate Dropdown with jQuery AJAX in Laravel 8</title>
</head>
<body>
<!-- Department Dropdown -->
Department : <select id='sel_depart' name='sel_depart'>
<option value='0'>-- Select department --</option>
<!-- Read Departments -->
@foreach($departments['data'] as $department)
<option value='{{ $department->id }}'>{{ $department->name }}</option>
@endforeach
</select>
<br><br>
<!-- Department Employees Dropdown -->
Employee : <select id='sel_emp' name='sel_emp'>
<option value='0'>-- Select Employee --</option>
</select>
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
// Department Change
$('#sel_depart').change(function(){
// Department id
var id = $(this).val();
// Empty the dropdown
$('#sel_emp').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'getEmployees/'+id,
type: 'get',
dataType: 'json',
success: function(response){
var len = 0;
if(response['data'] != null){
len = response['data'].length;
}
if(len > 0){
// Read data and create <option >
for(var i=0; i<len; i++){
var id = response['data'][i].id;
var name = response['data'][i].name;
var option = "<option value='"+id+"'>"+name+"</option>";
$("#sel_emp").append(option);
}
}
}
});
});
});
</script>
</body>
</html>
Nếu trên trang của bạn có nhiều menu thả xuống mà bạn muốn tự động điền thì hãy làm theo các bước tương tự để tải dữ liệu.
Nguồn: https://makitweb.com
1615040237
PHP jquery ajax POST request with MySQL. In this tutorial, you will learn how to create and submit a simple form in PHP using jQuery ajax post request. And how to submit a form data into MySQL database without the whole page refresh or reload. And also you will learn how to show an error message to the user if the user does not fill any form field.
And this tutorial also guide on how to send data to MySQL database using AJAX + jQuery + PHP without reloading the whole page and show a client-side validation error message if it has an error in the form.
Just follow the few below steps and easily create and submit ajax form in PHP and MySQL with client-side validation.
https://www.tutsmake.com/php-jquery-ajax-post-tutorial-example/
#jquery ajax serialize form data example #submit form using ajax in php example #save form data using ajax in php #how to insert form data using ajax in php #php jquery ajax form submit example #jquery ajax and jquery post form submit example with php
1597487472
Here, i will show you how to populate country state city in dropdown list in php mysql using ajax.
You can use the below given steps to retrieve and display country, state and city in dropdown list in PHP MySQL database using jQuery ajax onchange:
https://www.tutsmake.com/country-state-city-database-in-mysql-php-ajax/
#country state city drop down list in php mysql #country state city database in mysql php #country state city drop down list using ajax in php #country state city drop down list using ajax in php demo #country state city drop down list using ajax php example #country state city drop down list in php mysql ajax