article

Thursday, June 23, 2022

Laravel 9 Fetch records using jQuery AJAX

Laravel 9 Fetch records using jQuery AJAX

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory.

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

Create tables Model

php artisan make:model Product -m
C:\xampp\htdocs\laravel\laravelproject>php artisan make:model Product -m

Open new products migrations
yourproject/database/migrations
laravelproject\database\migrations\_create_products_table.php
//laravelproject\database\migrations\_create_products_table.php
<?php
 
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
 
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('price');
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\laravelproject>php artisan migrate
Migration table created successfully.
check database table

Creating Controller

php artisan make:controller ProductController
C:\xampp\htdocs\laravel\laravelproject>php artisan make:controller ProductController
change it with the following codes:

laravelproject\app\Http\Controllers\ProductController.php
//laravelproject\app\Http\Controllers\ProductController.php
<?php

namespace App\Http\Controllers;
use App\Models\Product; //add Product Model

use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index(){
        return view('ajaxdata');
     }
   
     public function getproducts($id = 0){
   
        if($id==0){ 
           $product = Product::orderby('id','asc')->select('*')->get(); 
        }else{   
           $product = Product::select('*')->where('id', $id)->get(); 
        }
        // Fetch all records
        $userData['data'] = $product;
   
        echo json_encode($userData);
        exit;
     }
}
Create Views
laravelproject\resources\views\ajaxdata.blade.php
//laravelproject\resources\views\ajaxdata.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Fetch records using jQuery AJAX - Cairocoders</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script> 
</head>
<body>
<div class="container">
    <h2>Laravel 9 Fetch records using jQuery AJAX </h2>
    <div class="row">
        <div class="col-lg-2">
            <input type='text' id='search' name='search' placeholder='Enter product id 1-27' class="form-control">
        </div>
        <div class="col-lg-10">
            <input type='button' value='Search' id='but_search' class="btn btn-success">
        </div>
    </div>
    <p><br/><input type='button' value='Fetch all records' id='but_fetchall' class="btn btn-success"></p>
    <table class="table table-bordered table-striped" id="productTable">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Price</th>               
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
<script type='text/javascript'>
    $(document).ready(function(){

       // Fetch all records
       $('#but_fetchall').click(function(){
	        fetchRecords(0);
       });

       // Search by id
        $('#but_search').click(function(){
            var userid = Number($('#search').val().trim());
            if(userid > 0){
                fetchRecords(userid);
            }
        });

    });

     function fetchRecords(id){
       $.ajax({
         url: 'getproducts/'+id,
         type: 'get',
         dataType: 'json',
         success: function(response){

           var len = 0;
           $('#productTable 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 name = response['data'][i].name;
                 var price = response['data'][i].price;

                 var tr_str = "<tr>" +
                   "<td>" + (i+1) + "</td>" +
                   "<td>" + name + "</td>" +
                   "<td>" + price + "</td>" +
                 "</tr>";

                 $("#productTable tbody").append(tr_str);
              }
           }else{
              var tr_str = "<tr>" +
                  "<td colspan='4'>No record found.</td>" +
              "</tr>";

              $("#productTable tbody").append(tr_str);
           }

         }
       });
    }
</script>
</body>
</html>
Creating Routes
laravelproject\routes\web.php
//laravelproject\routes\web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController; //add ProductController

//Route::get('/', function () {
//    return view('welcome');
//});

Route::get('/', [ProductController::class, 'index']);
Route::get('/getproducts/{id}', [ProductController::class, 'getproducts']);
Run C:\xampp\htdocs\laravel\laravelproject>php artisan serve Starting Laravel development server: http://127.0.0.1:8000

Related Post