笹田  洋介

笹田 洋介

1658529960

如何在 Laravel 8 中使用 JQuery AJAX 在 Select2 中加載 MySQL 數據

Select2 很容易在元素上初始化。它允許使用和不使用 AJAX 加載數據。

在本教程中,我將展示如何在 Laravel 8 項目中使用 jQuery AJAX 在 select2 中加載 MySQL 數據庫數據。

1. 數據庫配置

打開.env文件。

指定主機、數據庫名稱、用戶名和密碼。

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=

2.表結構

  • employees使用遷移創建 表並添加一些記錄。
php artisan make:migration create_employees_table
  • database/migrations/ 現在,從項目根目錄導航到 文件夾。
  • 找到一個以 結尾的 PHP 文件create_employees_table 並打開它。
  • 在方法中定義表結構 up() 。
public function up()
{
    Schema::create('employees', function (Blueprint $table) {
        $table->id();
        $table->string('username');
        $table->string('name');
        $table->string('email');
        $table->timestamps();
    });
}
  • 運行遷移 -
php artisan migrate
  • 表已創建。

3. 型號

創建Employees模型。

php artisan make:model Employees
  • 使用該屬性指定可批量分配的模型屬性 - 用戶名、姓名和電子郵件$fillable 。

完成的代碼

<?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'
    ];
}

4.控制器

創建一個 EmployeesController 控制器。

php artisan make:controller EmployeesController

創建 2 個方法 –

  • index() -加載 index視圖。
  • getEmployees() –此方法用於處理 AJAX 請求。

將 POST 搜索值分配給$search變量。

如果$search為空,則從employees表中獲取 5 條記錄並分配給,$employees否則,使用 選擇字段中$search存在值的5 條記錄。namelike

循環並使用和鍵$employees初始化$response數組。idtext

以 JSON 格式返回 $response 。

完成的代碼

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employees;

class EmployeesController extends Controller {

   public function index(){

     // Load index view
     return view('index');
   }

   // Fetch records
   public function getEmployees(Request $request){
      $search = $request->search;

      if($search == ''){
         $employees = Employees::orderby('name','asc')->select('id','name')->limit(5)->get();
      }else{
         $employees = Employees::orderby('name','asc')->select('id','name')->where('name', 'like', '%' .$search . '%')->limit(5)->get();
      }

      $response = array();
      foreach($employees as $employee){
         $response[] = array(
              "id"=>$employee->id,
              "text"=>$employee->name
         );
      }
      return response()->json($response); 
   } 
}

5. 路線

  • 打開 routes/web.php 文件。
  • 定義 2 條路線 –
    • / - 加載索引視圖。
    • /getEmployees –這用於發送 AJAX POST 請求以獲取員工列表。
<?php 
use Illuminate\Support\Facades\Route; 
use App\Http\Controllers\EmployeesController; 

Route::get('/', [EmployeesController::class, 'index']); 
Route::post('/getEmployees', [EmployeesController::class, 'getEmployees'])->name('getEmployees');

6.查看

在文件夾中創建一個新 index.blade.php 文件 resources/views/ 。

HTML –

  • <meta >存儲在標籤中的 CSRF 令牌 。
  • 包括 select2 和 jQuery 庫。
  • 創建一個 <select id='sel_emp' > 元素。

jQuery –

  • 從元標記讀取 csrf_token並分配給CSRF_TOKEN 變量。
  • #sel_emp在元素上初始化 select2 。
  • 使用'ajax'選項將 AJAX POST 請求發送到'getEmployees'. 設置dataType: 'json'
  • 將 data鍵入的值和 CSRF 令牌作為數據傳遞​​ - _token: CSRF_TOKEN, search: params.term
  • 使用 處理 AJAX 響應 processResultsresults 用 初始化 response

完成的代碼

<!DOCTYPE html>
<html>
<head>
   <title>How to Load data using jQuery AJAX in Select2 – Laravel 8</title>

   <!-- Meta -->
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <meta charset="utf-8">
   <meta name="csrf-token" content="{{ csrf_token() }}">

   <!-- CSS -->
   <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

   <!-- Script -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

</head>
<body>

   <!-- For defining select2 -->
   <select id='sel_emp' style='width: 200px;'>
      <option value='0'>-- Select employee --</option>
   </select>

   <!-- Script -->
   <script type="text/javascript">
   // CSRF Token
   var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
   $(document).ready(function(){

     $( "#sel_emp" ).select2({
        ajax: { 
          url: "{{route('getEmployees')}}",
          type: "post",
          dataType: 'json',
          delay: 250,
          data: function (params) {
            return {
               _token: CSRF_TOKEN,
               search: params.term // search term
            };
          },
          processResults: function (response) {
            return {
              results: response
            };
          },
          cache: true
        }

     });

   });
   </script>
</body>
</html>

7. 演示

查看演示


8. 結論

在示例中,我在從表中獲取記錄時將限制設置為 5。如果要選擇所有記錄,可以將其刪除,也可以根據需要進行調整。

Select2 返迴響應必須有idtext鍵,否則,數據將無法正確加載。

來源:  https ://makitweb.com

#php #ajax #laravel #mysql 

What is GEEK

Buddha Community

如何在 Laravel 8 中使用 JQuery AJAX 在 Select2 中加載 MySQL 數據
笹田  洋介

笹田 洋介

1658529960

如何在 Laravel 8 中使用 JQuery AJAX 在 Select2 中加載 MySQL 數據

Select2 很容易在元素上初始化。它允許使用和不使用 AJAX 加載數據。

在本教程中,我將展示如何在 Laravel 8 項目中使用 jQuery AJAX 在 select2 中加載 MySQL 數據庫數據。

1. 數據庫配置

打開.env文件。

指定主機、數據庫名稱、用戶名和密碼。

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=

2.表結構

  • employees使用遷移創建 表並添加一些記錄。
php artisan make:migration create_employees_table
  • database/migrations/ 現在,從項目根目錄導航到 文件夾。
  • 找到一個以 結尾的 PHP 文件create_employees_table 並打開它。
  • 在方法中定義表結構 up() 。
public function up()
{
    Schema::create('employees', function (Blueprint $table) {
        $table->id();
        $table->string('username');
        $table->string('name');
        $table->string('email');
        $table->timestamps();
    });
}
  • 運行遷移 -
php artisan migrate
  • 表已創建。

3. 型號

創建Employees模型。

php artisan make:model Employees
  • 使用該屬性指定可批量分配的模型屬性 - 用戶名、姓名和電子郵件$fillable 。

完成的代碼

<?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'
    ];
}

4.控制器

創建一個 EmployeesController 控制器。

php artisan make:controller EmployeesController

創建 2 個方法 –

  • index() -加載 index視圖。
  • getEmployees() –此方法用於處理 AJAX 請求。

將 POST 搜索值分配給$search變量。

如果$search為空,則從employees表中獲取 5 條記錄並分配給,$employees否則,使用 選擇字段中$search存在值的5 條記錄。namelike

循環並使用和鍵$employees初始化$response數組。idtext

以 JSON 格式返回 $response 。

完成的代碼

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employees;

class EmployeesController extends Controller {

   public function index(){

     // Load index view
     return view('index');
   }

   // Fetch records
   public function getEmployees(Request $request){
      $search = $request->search;

      if($search == ''){
         $employees = Employees::orderby('name','asc')->select('id','name')->limit(5)->get();
      }else{
         $employees = Employees::orderby('name','asc')->select('id','name')->where('name', 'like', '%' .$search . '%')->limit(5)->get();
      }

      $response = array();
      foreach($employees as $employee){
         $response[] = array(
              "id"=>$employee->id,
              "text"=>$employee->name
         );
      }
      return response()->json($response); 
   } 
}

5. 路線

  • 打開 routes/web.php 文件。
  • 定義 2 條路線 –
    • / - 加載索引視圖。
    • /getEmployees –這用於發送 AJAX POST 請求以獲取員工列表。
<?php 
use Illuminate\Support\Facades\Route; 
use App\Http\Controllers\EmployeesController; 

Route::get('/', [EmployeesController::class, 'index']); 
Route::post('/getEmployees', [EmployeesController::class, 'getEmployees'])->name('getEmployees');

6.查看

在文件夾中創建一個新 index.blade.php 文件 resources/views/ 。

HTML –

  • <meta >存儲在標籤中的 CSRF 令牌 。
  • 包括 select2 和 jQuery 庫。
  • 創建一個 <select id='sel_emp' > 元素。

jQuery –

  • 從元標記讀取 csrf_token並分配給CSRF_TOKEN 變量。
  • #sel_emp在元素上初始化 select2 。
  • 使用'ajax'選項將 AJAX POST 請求發送到'getEmployees'. 設置dataType: 'json'
  • 將 data鍵入的值和 CSRF 令牌作為數據傳遞​​ - _token: CSRF_TOKEN, search: params.term
  • 使用 處理 AJAX 響應 processResultsresults 用 初始化 response

完成的代碼

<!DOCTYPE html>
<html>
<head>
   <title>How to Load data using jQuery AJAX in Select2 – Laravel 8</title>

   <!-- Meta -->
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <meta charset="utf-8">
   <meta name="csrf-token" content="{{ csrf_token() }}">

   <!-- CSS -->
   <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

   <!-- Script -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

</head>
<body>

   <!-- For defining select2 -->
   <select id='sel_emp' style='width: 200px;'>
      <option value='0'>-- Select employee --</option>
   </select>

   <!-- Script -->
   <script type="text/javascript">
   // CSRF Token
   var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
   $(document).ready(function(){

     $( "#sel_emp" ).select2({
        ajax: { 
          url: "{{route('getEmployees')}}",
          type: "post",
          dataType: 'json',
          delay: 250,
          data: function (params) {
            return {
               _token: CSRF_TOKEN,
               search: params.term // search term
            };
          },
          processResults: function (response) {
            return {
              results: response
            };
          },
          cache: true
        }

     });

   });
   </script>
</body>
</html>

7. 演示

查看演示


8. 結論

在示例中,我在從表中獲取記錄時將限制設置為 5。如果要選擇所有記錄,可以將其刪除,也可以根據需要進行調整。

Select2 返迴響應必須有idtext鍵,否則,數據將無法正確加載。

來源:  https ://makitweb.com

#php #ajax #laravel #mysql 

Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

I am Developer

1593933651

Laravel 7 Ajax Dynamic Dependent Dropdown

In this tutorial i will share with you how to create dependent dropdown using ajax in laravel. Or how to create selected subcategories dropdown based on selected category dropdown using jQuery ajax in laravel apps.

As well as learn, how to retrieve data from database on onchange select category dropdown using jQuery ajax in drop down list in laravel.

Laravel Ajax Dynamic Dependent Dropdown Tutorial

Follow the below steps and implement dependent dropdown using jQuery ajax in laravel app:

  1. Step 1: Install Laravel New App
  2. Step 2: Add Database Details
  3. Step 3: Create Model and Migration
  4. Step 4: Add Routes
  5. Step 5: Create Controllers By Artisan
  6. Step 6: Create Blade Views
  7. Step 7: Run Development Server

Originally published at https://www.tutsmake.com/laravel-dynamic-dependent-dropdown-using-ajax-example

#laravel jquery ajax categories and subcategories select dropdown #jquery ajax dynamic dependent dropdown in laravel 7 #laravel dynamic dependent dropdown using ajax #display category and subcategory in laravel #onchange ajax jquery in laravel #how to make dynamic dropdown in laravel

I am Developer

1617089618

Laravel 8 Tutorial for Beginners

Hello everyone! I just updated this tutorial for Laravel 8. In this tutorial, we’ll go through the basics of the Laravel framework by building a simple blogging system. Note that this tutorial is only for beginners who are interested in web development but don’t know where to start. Check it out if you are interested: Laravel Tutorial For Beginners

Laravel is a very powerful framework that follows the MVC structure. It is designed for web developers who need a simple, elegant yet powerful toolkit to build a fully-featured website.

Recommended:-Laravel Try Catch

#laravel 8 tutorial #laravel 8 tutorial crud #laravel 8 tutorial point #laravel 8 auth tutorial #laravel 8 project example #laravel 8 tutorial for beginners

I am Developer

1599536794

Laravel 8 New Features | Release Notes - Tuts Make

In this post, i will show you what’s new in laravel 8 version.

#What’s new in Laravel 8?

  • 1 - Change Path Of Default Models Directory
  • 2 - Removed Controllers Namespace Prefix
  • 3 - Enhancements on php artisan serve
  • 4 - Enhanced Rate Limiting
  • 5 - Enhanced on Route Caching
  • 6 - Update on Pagination Design
  • 8 - Dynamic Blade Componenets
  • 7 - Update Syntax for Closure Based Event Listeners
  • 8 - Queueable Model Event Listeners
  • 9 - Maintenance mode: secret access
  • 10 - Maintenance mode: pre-rendered page
  • 11 - Queued job batching
  • 12 - Queue backoff()
  • 13 - Laravel Factory

https://www.tutsmake.com/laravel-8-new-features-release-notes/

#laravel 8 features #laravel 8 release date #laravel 8 tutorial #news - laravel 8 new features #what's new in laravel 8 #laravel 8 release notes