article

Saturday, October 29, 2022

Laravel 9 Jquery Ajax Example

Laravel 9 Jquery Ajax Example

Download Laravel App

composer create-project --prefer-dist laravel/laravel my-app
C:\xampp\htdocs\laravel>composer create-project --prefer-dist laravel/laravel my-app

Connecting our Database

open .env file root directory.

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

Create Controller
php artisan make:controller ProductsController
C:\xampp\htdocs\laravel\my-app>php artisan make:controller ProductsController
app/Http/Controllers/ProductsController.php
//app/Http/Controllers/ProductsController.php
<?php
namespace App\Http\Controllers;

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

class ProductsController extends Controller
{
    public function create() {
        return view('create');
    }

    public function save(Request $request) {
        $product = new Product;
        $product->product_name = $request->input('product_name');
        $product->product_description = $request->input('product_description');
        $product->save();

        return response()->json(['success'=>'New Product successfully added.']);
    }
}
Database Migration
php artisan make:model Product -m
C:\xampp\htdocs\laravel\my-app>php artisan make:model Product -m
database/migrations/create_products_table.php
//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
{
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('product_name');
            $table->text('product_description');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('products');
    }
};
run this migration
C:\xampp\htdocs\laravel\my-app>php artisan migrate

View Blade
resources/views/create.blade.php
//resources/views/create.blade.php
<!DOCTYPE html>
<html>
<head>
	<title>Laravel 9 Jquery Ajax Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <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>
    <meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<body>
    <div class="container">
        <h1>Laravel 9 Jquery Ajax Example</h1>
		<div id="message_display"></div>
        <form id="products">
            <div class="mb-3">
                <label>Product name:</label>
                <input type="text" name="product_name" id="product_name" class="form-control" placeholder="Product Name" required>
            </div>

            <div class="mb-3">
                <label>Product Description:</label>
				<textarea name="product_description" id="product_description" placeholder="Product Description" class="form-control"></textarea>
            </div>

            <div class="mb-3">
                <button class="btn btn-success btn-submit add_product">Submit</button>
            </div>
        </form>
    </div>
</body>
<script type="text/javascript">
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$(".add_product").click(function(e) {
    e.preventDefault();
    var product_name = $("#product_name").val();
    var product_description = $("#product_description").val();

	if(product_name == '' || product_description == '') {
		$('#message_display').html('<div class="alert alert-danger">Please input data.</div>');
		$('#message_display div').delay(1000).hide(0);
		return false;
	}

    $.ajax({
        type: 'POST',
        url: "{{ route('save') }}",
        data: {
            product_name: product_name,
            product_description: product_description
        },
        success: function(data) {
			$('#message_display').html('<div class="alert alert-success">' + data.success + '</div>');
			$('#message_display div').delay(2000).hide(0);
			$('#products')[0].reset();
        }
    });
});
</script>
</html>
Routes
routes/web.php
//routes/web.php
<?php
use Illuminate\Support\Facades\Route;

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

Route::get('product-create', 'App\Http\Controllers\ProductsController@create');
Route::post('product-save', 'App\Http\Controllers\ProductsController@save')->name('save');
Run C:\xampp\htdocs\laravel\my-app>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Related Post