1658754480
La recuperación de datos es uno de los requisitos básicos cuando se trabaja con la base de datos utilizando AJAX.
Mostrar datos en función del inicio de sesión del usuario, generar un informe, etc.
En este tutorial, muestro cómo puede obtener registros de la base de datos MySQL usando jQuery AJAX en Laravel 8.
Abrir .env
archivo.
Especifique el host, el nombre de la base de datos, el nombre de usuario y la contraseña.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=
employees
mediante la migración.php artisan make:migration create_employees_table
database/migration/
la carpeta desde la raíz del proyecto.create_employees_table
y ábralo.up()
método.public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('username');
$table->string('name');
$table->string('email');
$table->timestamps();
});
}
php artisan migrate
Employees
modelo.php artisan make:model Employees
app/Models/Employees.php
archivo.$fillable
propiedad.Código completado
<?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'
];
}
Crea un EmployeesController
controlador.
php artisan make:controller EmployeesController
Crear 3 métodos –
employees
vista.Obtenga todos los registros de la employees
tabla y asígnelos a $employees
. Asignar $employees
a $response['data']
matriz.
Retorna $response
Array en formato JSON.
$userid
variable.Buscar registro por id de la employees
tabla. Asignar $employees
a $response['data']
matriz.
Retorna $response
Array en formato JSON.
Código completado
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employees;
class EmployeesController extends Controller
{
public function index(){
return view('employees');
}
public function getUsers(){
$employees = Employees::orderby('id','asc')->select('*')->get();
// Fetch all records
$response['data'] = $employees;
return response()->json($response);
}
public function getUserbyid(Request $request){
$userid = $request->userid;
$employees = Employees::select('*')->where('id', $userid)->get();
// Fetch all records
$response['data'] = $employees;
return response()->json($response);
}
}
routes/web.php
archivo.<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeesController;
Route::get('/', [EmployeesController::class, 'index']);
Route::get('/getUsers', [EmployeesController::class, 'getUsers']);
Route::post('/getUserbyid', [EmployeesController::class, 'getUserbyid']);
Crear employees.blade.php
archivo en resources/views/
.
HTML
Cree un cuadro de texto para ingresar la identificación del usuario y 2 botones. El primer botón para obtener el registro por ID de usuario y el segundo botón para obtener la lista de todos los usuarios.
Úselo <table id="empTable">
para listar registros usando jQuery AJAX.
Guion
Lea el token CSRF de la <meta >
etiqueta y asígnelo a la CSRF_TOKEN
variable.
Defina evento de clic en #but_fetchall
y #but_search
.
Si #but_fetchall
se hace clic en , envíe la solicitud AJAX GET a 'getUsers'
, configure dataType: 'json'
. En una devolución de llamada exitosa, pase response
a la createRows()
función para crear filas de tabla.
Si #but_search
se hace clic, lea el valor del cuadro de texto y asígnelo a la userid
variable. Envíe la solicitud AJAX POST a 'getUserbyid'
, pase CSRF_TOKEN
y userid
como datos, configure dataType: 'json'
. En una devolución de llamada exitosa, pase response
a la createRows()
función para crear filas de tabla.
createRows() – Vacío <table> <tbody>
. Si response['data']
la longitud es mayor que 0, haga un bucle en response['data']
y cree uno nuevo <tr >
y agréguelo; de #empTable tbody
lo contrario, agregue "No se encontró ningún registro" <tr>
en <tbody>
.
Código completado
<!DOCTYPE html>
<html>
<head>
<title>How to Fetch records from MySQL with jQuery AJAX - 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() }}">
</head>
<body>
<input type='text' id='search' name='search' placeholder='Enter userid 1-7'>
<input type='button' value='Search' id='but_search'>
<br/>
<input type='button' value='Fetch all records' id='but_fetchall'>
<!-- Table -->
<table border='1' id='empTable' style='border-collapse: collapse;'>
<thead>
<tr>
<th>S.no</th>
<th>Username</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody></tbody>
</table>
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type='text/javascript'>
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(document).ready(function(){
// Fetch all records
$('#but_fetchall').click(function(){
// AJAX GET request
$.ajax({
url: 'getUsers',
type: 'get',
dataType: 'json',
success: function(response){
createRows(response);
}
});
});
// Search by userid
$('#but_search').click(function(){
var userid = Number($('#search').val().trim());
if(userid > 0){
// AJAX POST request
$.ajax({
url: 'getUserbyid',
type: 'post',
data: {_token: CSRF_TOKEN, userid: userid},
dataType: 'json',
success: function(response){
createRows(response);
}
});
}
});
});
// Create table rows
function createRows(response){
var len = 0;
$('#empTable tbody').empty(); // Empty <tbody>
if(response['data'] != null){
len = response['data'].length;
}
if(len > 0){
for(var i=0; i<len; i++){
var id = response['data'][i].id;
var username = response['data'][i].username;
var name = response['data'][i].name;
var email = response['data'][i].email;
var tr_str = "<tr>" +
"<td align='center'>" + (i+1) + "</td>" +
"<td align='center'>" + username + "</td>" +
"<td align='center'>" + name + "</td>" +
"<td align='center'>" + email + "</td>" +
"</tr>";
$("#empTable tbody").append(tr_str);
}
}else{
var tr_str = "<tr>" +
"<td align='center' colspan='4'>No record found.</td>" +
"</tr>";
$("#empTable tbody").append(tr_str);
}
}
</script>
</body>
</html>
En el ejemplo, le mostré las formas GET y POST de recuperar datos.
Se requiere token CSRF al enviar solicitudes AJAX POST.
Fuente: https://makitweb.com
1658754480
La recuperación de datos es uno de los requisitos básicos cuando se trabaja con la base de datos utilizando AJAX.
Mostrar datos en función del inicio de sesión del usuario, generar un informe, etc.
En este tutorial, muestro cómo puede obtener registros de la base de datos MySQL usando jQuery AJAX en Laravel 8.
Abrir .env
archivo.
Especifique el host, el nombre de la base de datos, el nombre de usuario y la contraseña.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=
employees
mediante la migración.php artisan make:migration create_employees_table
database/migration/
la carpeta desde la raíz del proyecto.create_employees_table
y ábralo.up()
método.public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('username');
$table->string('name');
$table->string('email');
$table->timestamps();
});
}
php artisan migrate
Employees
modelo.php artisan make:model Employees
app/Models/Employees.php
archivo.$fillable
propiedad.Código completado
<?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'
];
}
Crea un EmployeesController
controlador.
php artisan make:controller EmployeesController
Crear 3 métodos –
employees
vista.Obtenga todos los registros de la employees
tabla y asígnelos a $employees
. Asignar $employees
a $response['data']
matriz.
Retorna $response
Array en formato JSON.
$userid
variable.Buscar registro por id de la employees
tabla. Asignar $employees
a $response['data']
matriz.
Retorna $response
Array en formato JSON.
Código completado
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employees;
class EmployeesController extends Controller
{
public function index(){
return view('employees');
}
public function getUsers(){
$employees = Employees::orderby('id','asc')->select('*')->get();
// Fetch all records
$response['data'] = $employees;
return response()->json($response);
}
public function getUserbyid(Request $request){
$userid = $request->userid;
$employees = Employees::select('*')->where('id', $userid)->get();
// Fetch all records
$response['data'] = $employees;
return response()->json($response);
}
}
routes/web.php
archivo.<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeesController;
Route::get('/', [EmployeesController::class, 'index']);
Route::get('/getUsers', [EmployeesController::class, 'getUsers']);
Route::post('/getUserbyid', [EmployeesController::class, 'getUserbyid']);
Crear employees.blade.php
archivo en resources/views/
.
HTML
Cree un cuadro de texto para ingresar la identificación del usuario y 2 botones. El primer botón para obtener el registro por ID de usuario y el segundo botón para obtener la lista de todos los usuarios.
Úselo <table id="empTable">
para listar registros usando jQuery AJAX.
Guion
Lea el token CSRF de la <meta >
etiqueta y asígnelo a la CSRF_TOKEN
variable.
Defina evento de clic en #but_fetchall
y #but_search
.
Si #but_fetchall
se hace clic en , envíe la solicitud AJAX GET a 'getUsers'
, configure dataType: 'json'
. En una devolución de llamada exitosa, pase response
a la createRows()
función para crear filas de tabla.
Si #but_search
se hace clic, lea el valor del cuadro de texto y asígnelo a la userid
variable. Envíe la solicitud AJAX POST a 'getUserbyid'
, pase CSRF_TOKEN
y userid
como datos, configure dataType: 'json'
. En una devolución de llamada exitosa, pase response
a la createRows()
función para crear filas de tabla.
createRows() – Vacío <table> <tbody>
. Si response['data']
la longitud es mayor que 0, haga un bucle en response['data']
y cree uno nuevo <tr >
y agréguelo; de #empTable tbody
lo contrario, agregue "No se encontró ningún registro" <tr>
en <tbody>
.
Código completado
<!DOCTYPE html>
<html>
<head>
<title>How to Fetch records from MySQL with jQuery AJAX - 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() }}">
</head>
<body>
<input type='text' id='search' name='search' placeholder='Enter userid 1-7'>
<input type='button' value='Search' id='but_search'>
<br/>
<input type='button' value='Fetch all records' id='but_fetchall'>
<!-- Table -->
<table border='1' id='empTable' style='border-collapse: collapse;'>
<thead>
<tr>
<th>S.no</th>
<th>Username</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody></tbody>
</table>
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type='text/javascript'>
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(document).ready(function(){
// Fetch all records
$('#but_fetchall').click(function(){
// AJAX GET request
$.ajax({
url: 'getUsers',
type: 'get',
dataType: 'json',
success: function(response){
createRows(response);
}
});
});
// Search by userid
$('#but_search').click(function(){
var userid = Number($('#search').val().trim());
if(userid > 0){
// AJAX POST request
$.ajax({
url: 'getUserbyid',
type: 'post',
data: {_token: CSRF_TOKEN, userid: userid},
dataType: 'json',
success: function(response){
createRows(response);
}
});
}
});
});
// Create table rows
function createRows(response){
var len = 0;
$('#empTable tbody').empty(); // Empty <tbody>
if(response['data'] != null){
len = response['data'].length;
}
if(len > 0){
for(var i=0; i<len; i++){
var id = response['data'][i].id;
var username = response['data'][i].username;
var name = response['data'][i].name;
var email = response['data'][i].email;
var tr_str = "<tr>" +
"<td align='center'>" + (i+1) + "</td>" +
"<td align='center'>" + username + "</td>" +
"<td align='center'>" + name + "</td>" +
"<td align='center'>" + email + "</td>" +
"</tr>";
$("#empTable tbody").append(tr_str);
}
}else{
var tr_str = "<tr>" +
"<td align='center' colspan='4'>No record found.</td>" +
"</tr>";
$("#empTable tbody").append(tr_str);
}
}
</script>
</body>
</html>
En el ejemplo, le mostré las formas GET y POST de recuperar datos.
Se requiere token CSRF al enviar solicitudes AJAX POST.
Fuente: https://makitweb.com
1595201363
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'
];
}
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
1593933651
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.
Follow the below steps and implement dependent dropdown using jQuery ajax in laravel app:
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
1617089618
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.
#laravel 8 tutorial #laravel 8 tutorial crud #laravel 8 tutorial point #laravel 8 auth tutorial #laravel 8 project example #laravel 8 tutorial for beginners
1599536794
In this post, i will show you what’s new in laravel 8 version.
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