article

Monday, April 11, 2022

Laravel 9 CRUD (Create, Read, Update and Delete) with Image Upload

Laravel 9 CRUD (Create, Read, Update and Delete) with Image Upload

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

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=laravel9
DB_USERNAME=root
DB_PASSWORD=

Database Migration 

php artisan make:migration create_products_table --create=products

C:\xampp\htdocs\laravel9\blog>php artisan make:migration create_products_table --create=products

After this command you will find one file in following path database/migrations Edit code 

blog\database\migrations\create_products_table.php
//blog\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->id();
            $table->string('name');
            $table->text('detail');
            $table->string('image');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
};
Run this migration

php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Creating Controller

php artisan make:controller ProductController --resource --model=Product
C:\xampp\htdocs\laravel9\blog>php artisan make:controller ProductController --resource --model=Product
controller created file located at : youproject/app/Http/Controller
blog\app\Http\Controllers\ProductController.php
controller will create seven methods by default as index, create, store, show, edit, update and destroy
change it with the following codes:
blog\app\Http\Controllers\ProductController.php
//blog\app\Http\Controllers\ProductController.php
<?php

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = Product::latest()->paginate(5);
    
        return view('index',compact('products'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
  
        $input = $request->all();
  
        if ($image = $request->file('image')) {
            $destinationPath = 'images/';
            $profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($destinationPath, $profileImage);
            $input['image'] = "$profileImage";
        }
    
        Product::create($input);
     
        return redirect()->route('index')
                        ->with('success','Product created successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show(Product $product)
    {
 
    	return view('show',compact('product'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit(Product $product)
    {
        return view('edit',compact('product'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Product $product)
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required'
        ]);
  
        $input = $request->all();
  
        if ($image = $request->file('image')) {
            $destinationPath = 'images/';
            $profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($destinationPath, $profileImage);
            $input['image'] = "$profileImage";
        }else{
            unset($input['image']);
        }
          
        $product->update($input);
    
        return redirect()->route('index')
                        ->with('success','Product updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {
        $product->delete();
     
        return redirect()->route('index')
                        ->with('success','Product deleted successfully');
    }
}
Edit Product Model app/Models/Product.php
blog/app/Models/Product.php
//blog/app/Models/Product.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'detail', 'image'
    ];
}
Creating Routes
blog\routes\web.php
//blog\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@index')->name('index');
Route::get('/create', 'ProductController@create')->name('create');
Route::post('store/', 'ProductController@store')->name('store');
Route::get('show/{product}', 'ProductController@show')->name('show');
Route::get('edit/{product}', 'ProductController@edit')->name('edit');
Route::put('edit/{product}','ProductController@update')->name('update');
Route::delete('/{product}','ProductController@destroy')->name('destroy');
Creating Views
blog\resources\views\app.blade.php
//blog\resources\views\app.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 CRUD (Create, Read, Update and Delete) with Image Upload</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    @yield('content')
</div>
</body>
</html>
blog\resources\views\index.blade.php
//blog\resources\views\index.blade.php
@extends('app')
 
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 9 CRUD (Create, Read, Update and Delete) with Image Upload</h2>
            </div>
            <div class="pull-right" style="margin-bottom:10px;">
            <a class="btn btn-success" href="{{ url('create') }}"> Create New Product</a>
            </div>
        </div>
    </div>
    
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif

    <table class="table table-bordered">
        <tr>
            <th>No</th>
            <th>Image</th>
            <th>Name</th>
            <th>Details</th>
            <th width="280px">Action</th>
        </tr>
        @foreach ($products as $product)
        <tr>
            <td>{{ ++$i }}</td>
            <td><img src="/images/{{ $product->image }}" width="100px"></td>
            <td>{{ $product->name }}</td>
            <td>{{ $product->detail }}</td>
            <td>
                <form action="{{ route('destroy',$product->id) }}" method="POST">
     
                    <a class="btn btn-info" href="{{ route('show',$product->id) }}">Show</a>
      
                    <a class="btn btn-primary" href="{{ route('edit',$product->id) }}">Edit</a>
     
                    @csrf
                    @method('DELETE')
        
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>
    
    {!! $products->links() !!}

@endsection
blog\resources\views\create.blade.php
//blog\resources\views\create.blade.php
@extends('app')
  
@section('content')
<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Add New Product</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="{{ url('/') }}"> Back</a>
        </div>
    </div>
</div>
     
@if ($errors->any())
    <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<form action="{{ route('store') }}" method="POST" enctype="multipart/form-data">
    @csrf
    
     <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                <input type="text" name="name" class="form-control" placeholder="Name">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Detail:</strong>
                <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea>
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Image:</strong>
                <input type="file" name="image" class="form-control" placeholder="image">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>
     
</form>
@endsection
blog\resources\views\show.blade.php
//blog\resources\views\show.blade.php
@extends('app')
 
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2> Show Product</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ url('/') }}"> Back</a>
            </div>
        </div>
    </div>
     
    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                {{ $product->name }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Details:</strong>
                {{ $product->detail }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Image:</strong>
                <img src="/images/{{ $product->image }}" width="500px">
            </div>
        </div>
    </div>
@endsection
blog\resources\views\edit.blade.php
//blog\resources\views\edit.blade.php
@extends('app')
 
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Edit Product</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('index') }}"> Back</a>
            </div>
        </div>
    </div>
     
    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    
    <form action="{{ route('update',$product->id) }}" method="POST" enctype="multipart/form-data">
        @csrf
        @method('PUT')
     
         <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Name:</strong>
                    <input type="text" name="name" value="{{ $product->name }}" class="form-control" placeholder="Name">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Detail:</strong>
                    <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ $product->detail }}</textarea>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Image:</strong>
                    <input type="file" name="image" class="form-control" placeholder="image">
                    <img src="/images/{{ $product->image }}" width="300px">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
              <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>
     
    </form>
@endsection
Edit RouteServiceProvider.php
blog\app\Providers\RouteServiceProvider.php
uncomment protected $namespace = 'App\\Http\\Controllers';

Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Saturday, April 9, 2022

Laravel Fetch Data using Jquery Ajax and show data in modal with pagination | Laravel 9

Laravel Fetch Data using Jquery Ajax and show data in modal with pagination | Laravel 9

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

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=laravel9
DB_USERNAME=root
DB_PASSWORD=

Database Migration 

php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate

Create dummy records on users table and import it

php artisan tinker
  
User::factory()->count(20)->create()

C:\xampp\htdocs\laravel9\blog>php artisan tinker
Psy Shell v0.11.1 (PHP 8.0.13 — cli) by Justin Hileman
>>> User::factory()->count(20)->create()
[!] Aliasing 'User' to 'App\Models\User' for this Tinker session.

check database table user 20 dummy records added

Creating Controller

php artisan make:controller UserController 
C:\xampp\htdocs\laravel9\blog>php artisan make:controller UserController

controller created file located at :  youproject/app/Http/Controller
blog\app\Http\Controllers\UserController.php

change it with the following codes:
blog\app\Http\Controllers\UserController.php
//blog\app\Http\Controllers\UserController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User; //add model User

class UserController extends Controller
{
    public function index()
    {        
        $users = User::simplePaginate(5);
 
        return view('users', compact('users'));
    }
	
	public function show($id)
    {
        $user = User::find($id);
  
        return response()->json($user);
    }
}
Creating Routes
blog\routes\web.php
//blog\routes\web.php
<?php

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

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

Route::get('/', [UserController::class, 'index']);

Route::get('users/{id}', [UserController::class, 'show'])->name('users.show');
Creating Views
blog\resources\views\app.blade.php
//blog\resources\views\app.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Fetch Data using Jquery Ajax | Laravel 9</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<body>
<div class="container">
    @yield('content')
</div>

@yield('script')
</body>
</html>
blog\resources\views\users.blade.php
//blog\resources\views\users.blade.php
@extends('app')
 
@section('content')
<div class="row">
    <h1>Laravel Fetch Data using Jquery Ajax and show data in modal with pagination | Laravel 9</h1>
    <table class="table table-bordered data-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach($users as $user)
            <tr>
                <td>{{ $user->id }}</td>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
                <td>
                    <a 
                        href="javascript:void(0)" 
                        id="show-user" 
                        data-url="{{ route('users.show', $user->id) }}" 
                        class="btn btn-info"
                        >Show</a>
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>
    <div class="row">{{ $users->links() }}</div>

<!-- Modal -->
<div class="modal fade" id="userShowModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Show User</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p><strong>ID:</strong> <span id="user-id"></span></p>
        <p><strong>Name:</strong> <span id="user-name"></span></p>
        <p><strong>Email:</strong> <span id="user-email"></span></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

</div>
@endsection

@section('script')
<script type="text/javascript">
      
    $(document).ready(function () {
       
        $('body').on('click', '#show-user', function () {
          var userURL = $(this).data('url');
          $.get(userURL, function (data) {
              $('#userShowModal').modal('show');
              $('#user-id').text(data.id);
              $('#user-name').text(data.name);
              $('#user-email').text(data.email);
          })
       });
       
    });
  
</script>
@endsection
Edit RouteServiceProvider.php
blog\app\Providers\RouteServiceProvider.php
uncomment protected $namespace = 'App\\Http\\Controllers';

Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Friday, April 8, 2022

Laravel Jquery Ajax CRUD (Create, Read, Update and Delete) Bootstrap 5 Modal | Laravel 9

Laravel Jquery Ajax CRUD (Create, Read, Update and Delete) Bootstrap 5 Modal | Laravel 9

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

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=laravel9
DB_USERNAME=root
DB_PASSWORD=

Creating Controller

php artisan make:controller MemberController 
C:\xampp\htdocs\laravel9\blog>php artisan make:controller MemberController

controller created file located at :  youproject/app/Http/Controller
blog\app\Http\Controllers\MemberController.php

change it with the following codes:

blog\app\Http\Controllers\MemberController.php

//blog\app\Http\Controllers\MemberController.php
<?php

namespace App\Http\Controllers;

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

class MemberController extends Controller
{
    public function index(){
        return view('show');
    }
    
    public function getMembers(){
        $members = Member::all();
 
        return view('memberlist', compact('members'));
    }
	
	public function save(Request $request){
    	if ($request->ajax()){
    		// Create New Member
	    	$member = new Member;
	    	$member->firstname = $request->input('firstname');
	    	$member->lastname = $request->input('lastname');
	    	// Save Member
	  		$member->save();
    		
    		return response($member);
    	}
    }
	
	public function delete(Request $request){
    	if ($request->ajax()){
    		Member::destroy($request->id);
    	}
    }

    public function update(Request $request){
    	if ($request->ajax()){
    		$member = Member::find($request->id);
    		$member->firstname = $request->input('firstname');
    		$member->lastname = $request->input('lastname');

    		$member->update();
    		return response($member);
    	}
    }
}
Create Model

php artisan make:model Member -m
C:\xampp\htdocs\laravel9\blog>php artisan make:model Member -m

This will create our model in the form of Member.php file located : blog\app\Models\Member.php

we put -m when we create our model.
this will automatically make the migration for our model and you will see that in yourproject/database/migrations
blog\database\migrations\create_members_table.php

edit code blog\database\migrations\create_members_table.php
////blog\database\migrations\create_members_table.php
<?php
 
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
  
class CreateMembersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('members', function (Blueprint $table) {
            $table->increments('id');
            $table->string('firstname');
            $table->string('lastname');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('members');
    }
}
Database Migration

php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table created table created member

Creating Routes
blog\routes\web.php
//blog\routes\web.php
<?php
use Illuminate\Support\Facades\Route;

Route::get('/', 'MemberController@index');

Route::get('/show', 'MemberController@getMembers');

Route::post('/save', 'MemberController@save');

Route::post('/delete', 'MemberController@delete');

Route::post('/update', 'MemberController@update');
Creating Views
blog\resources\views\app.blade.php
//blog\resources\views\app.blade.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel Jquery Ajax CRUD (Create, Read, Update and Delete) | Laravel 9</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container">
    @yield('content')
</div>
@include('modal')

@yield('script')
</body>
</html>
blog\resources\views\memberlist.blade.php
//blog\resources\views\memberlist.blade.php
@foreach($members as $member)
	<tr>
		<td>{{ $member->firstname }}</td>
		<td>{{ $member->lastname }}</td>
		<td><a href='#' class='btn btn-success edit' data-id='{{ $member->id }}' data-first='{{ $member->firstname }}' data-last='{{ $member->lastname }}'> Edit</a> 
			<a href='#' class='btn btn-danger delete' data-id='{{ $member->id }}'> Delete</a>
		</td>
	</tr>
@endforeach
blog\resources\views\show.blade.php
//blog\resources\views\show.blade.php
@extends('app')
 
@section('content')
<h1 class="page-header text-center">Laravel Jquery Ajax CRUD (Create, Read, Update and Delete) Bootstrap 5 Modal | Laravel 9</h1>
<div class="row">
	<div class="col-md-10 col-md-offset-1">
		<h2>Members Table
			<button type="button" id="add" data-bs-toggle="modal" data-bs-target="#addnew" class="btn btn-primary pull-right"> Member</button>
		</h2>
	</div>
</div>
<div class="row">
	<div class="col-md-10 col-md-offset-1">
		<table class="table table-bordered table-responsive table-striped">
            <thead>
                <th>Fisrtname</th>
                <th>Lastname</th>
                <th>Action</th>
            </thead>
            <tbody id="memberBody">
            </tbody>
             
        </table>
	</div>
</div>
@endsection
 
@section('script')
    <script type="text/javascript">
        $(document).ready(function(){
 
 			$.ajaxSetup({
			    headers: {
			        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
			    }
			});
			
            showMember();
  
  			$('#addForm').on('submit', function(e){
				e.preventDefault();
				var form = $(this).serialize();
				var url = $(this).attr('action');
				$.ajax({
					type: 'POST',
					url: url,
					data: form,
					dataType: 'json',
					success: function(){
						$('#addnew').modal('hide');
						$('#addForm')[0].reset();
						showMember();
					}
				});
			});
			
			$(document).on('click', '.edit', function(event){
				event.preventDefault();
				var id = $(this).data('id');
				var firstname = $(this).data('first');
				var lastname = $(this).data('last');
				$('#editmodal').modal('show');
				$('#firstname').val(firstname);
				$('#lastname').val(lastname);
				$('#memid').val(id);
			});
			
			$(document).on('click', '.delete', function(event){
				event.preventDefault();
				var id = $(this).data('id');
				$('#deletemodal').modal('show');
				$('#deletemember').val(id);
			});
			
			$('#editForm').on('submit', function(e){
				e.preventDefault();
				var form = $(this).serialize();
				var url = $(this).attr('action');
				$.post(url,form,function(data){
					$('#editmodal').modal('hide');
					showMember();
				})
			});
			
			$('#deletemember').click(function(){
				var id = $(this).val();
				$.post("{{ URL::to('delete') }}",{id:id}, function(){
					$('#deletemodal').modal('hide');
					showMember();
				})
			});
			
        });
  
        function showMember(){ 
            $.get("{{ URL::to('show') }}", function(data){ 
                $('#memberBody').empty().html(data);
            })
        }
         
    </script>
@endsection
blog\resources\views\modal.blade.php
//blog\resources\views\modal.blade.php
<!-- Add Modal -->
<div class="modal fade" id="addnew" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="myModalLabel">Add New Member</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
		<div class="modal-body">
			<form action="{{ URL::to('save') }}" id="addForm">
			    <div class="mb-3">
				    <label for="firstname">Firstname</label>
				    <input type="text" name="firstname" class="form-control" placeholder="Input Firstname" required>
			    </div>
			    <div class="mb-3">
				    <label for="lastname">Lastname</label>
				    <input type="text" name="lastname" class="form-control" placeholder="Input Lastname" required>
			    </div>
		</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Save</button>
		</form>
      </div>
    </div>
  </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editmodal" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="myModalLabel">Edit Member</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
		<div class="modal-body">
			<form action="{{ URL::to('update') }}" id="editForm">
				<input type="hidden" id="memid" name="id">
			    <div class="mb-3">
				    <label for="firstname">Firstname</label>
				    <input type="text" name="firstname" id="firstname" class="form-control">
			    </div>
			    <div class="mb-3">
				    <label for="lastname">Lastname</label>
				    <input type="text" name="lastname" id="lastname" class="form-control">
			    </div>
		</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-success">Update</button>
		</form>
      </div>
    </div>
  </div>
</div>

<!-- Delete Modal -->
<div class="modal fade" id="deletemodal" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="myModalLabel">Delete Member</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
	  <div class="modal-body">
			<h4 class="text-center">Are you sure you want to delete Member?</h4>
	  </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" id="deletemember" class="btn btn-danger">Delete</button>
		</form>
      </div>
    </div>
  </div>
</div>
Edit RouteServiceProvider.php
blog\app\Providers\RouteServiceProvider.php
uncomment protected $namespace = 'App\\Http\\Controllers';

Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Thursday, April 7, 2022

Laravel Jquery Ajax List All Data | Laravel 9

Laravel Jquery Ajax List All Data | Laravel 9

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

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=laravel9
DB_USERNAME=root
DB_PASSWORD=

Creating Controller

php artisan make:controller MemberController 
C:\xampp\htdocs\laravel9\blog>php artisan make:controller MemberController

controller created file located at :  youproject/app/Http/Controller
blog\app\Http\Controllers\MemberController.php

change it with the following codes:

blog\app\Http\Controllers\MemberController.php
//blog\app\Http\Controllers\MemberController.php
<?php

namespace App\Http\Controllers;

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

class MemberController extends Controller
{
    public function index(){
    	return view('show');
    }

    public function getMembers(){
    	$members = Member::all();

    	return view('memberlist', compact('members'));
    }

}

Create Model

php artisan make:model Member -m

C:\xampp\htdocs\laravel9\blog>php artisan make:model Member -m

This will create our model in the form of Member.php file located : blog\app\Models\Member.php

we put -m when we create our model.
this will automatically make the migration for our model and you will see that in yourproject/database/migrations
blog\database\migrations\2022_04_07_054037_create_members_table.php

edit code 
blog\database\migrations\2022_04_07_054037_create_members_table.php
//blog\database\migrations\2022_04_07_054037_create_members_table.php
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
 
class CreateMembersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('members', function (Blueprint $table) {
            $table->increments('id');
            $table->string('firstname');
            $table->string('lastname');
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('members');
    }
}

Database Migration

php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table created table created member

Creating Routes

blog\routes\web.php
//blog\routes\web.php
<?php
use Illuminate\Support\Facades\Route;

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

Route::get('/', 'MemberController@index');
 
Route::get('/show', 'MemberController@getMembers');
Creating Views
blog\resources\views\app.blade.php
//blog\resources\views\app.blade.php
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="csrf-token" content="{{ csrf_token() }}">
	<title>Laravel Jquery Ajax List All Data | Laravel 9</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
<div class="container">
	@yield('content')
</div>
 
@yield('script')
</body>
</html>
blog\resources\views\memberlist.blade.php
//blog\resources\views\memberlist.blade.php
@foreach($members as $member)
	<tr>
		<td>{{ $member->firstname }}</td>
		<td>{{ $member->lastname }}</td>
		<td><a href='' class='btn btn-success' data-id='{{ $member->id }}'> Edit</a> 
			<a href='' class='btn btn-danger' data-id='{{ $member->id }}'> Delete</a>
		</td>
	</tr>
@endforeach
blog\resources\views\show.blade.php
//blog\resources\views\show.blade.php
@extends('app')
 
@section('content')
<h1 class="page-header text-center">Laravel Jquery Ajax List All Data | Laravel 9</h1>
<div class="row">
	<div class="col-md-10 col-md-offset-1">
		<h2>Members Table
			<button type="button" id="add" class="btn btn-primary pull-right"><i class="fa fa-plus"></i> Member</button>
		</h2>
	</div>
</div>
<div class="row">
	<div class="col-md-10 col-md-offset-1">
		<table class="table table-bordered table-responsive table-striped">
			<thead>
				<th>Fisrtname</th>
				<th>Lastname</th>
				<th>Action</th>
			</thead>
			<tbody id="memberBody">
			</tbody>
			
		</table>
	</div>
</div>
@endsection
 
@section('script')
	<script type="text/javascript">
		$(document).ready(function(){

			showMember();
 
		});
 
		function showMember(){ 
			$.get("{{ URL::to('show') }}", function(data){ 
				$('#memberBody').empty().html(data);
			})
		}
		
	</script>
@endsection


Edit RouteServiceProvider.php
blog\app\Providers\RouteServiceProvider.php
uncomment protected $namespace = 'App\\Http\\Controllers';

Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Wednesday, April 6, 2022

SwiftUI Infinite Scroll Load More Data github user API with sheet view

SwiftUI Infinite Scroll Load More Data github user API with sheet view

Github API
https://api.github.com/users?per_page=15

SDWebImage
https://github.com/SDWebImage/SDWebImageSwiftUI.git

https://docs.github.com/en/rest/reference/users#list-users

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import Combine
import SwiftUI

struct ContentView: View {
    @ObservedObject private var userViewModel = UserViewModel()
    
    @State var columns = Array(repeating: GridItem(.flexible(), spacing: 15), count: 2)
    
    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            HStack{
                 
                Text("GitHub User")
                    .font(.title)
                    .fontWeight(.bold)
                 
                Spacer()
                 
                Button {
                     
                } label: {
                 
                    Image(systemName: "rectangle.grid.1x2")
                        .font(.system(size: 24))
                        .foregroundColor(.black)
                }

            }
            .padding(.horizontal)
            .padding(.top,25)
             
            LazyVGrid(columns: self.columns,spacing: 25){
                 
                ForEach(userViewModel.users, id: \.id) { user in
                    UserRow(user: user)
                } 
                LoaderView(isFailed: userViewModel.isRequestFailed)
                    .onAppear(perform: fetchData)
                    .onTapGesture(perform: onTapLoadView)
            }
            .padding([.horizontal,.top])
        }
        .background(Color.black.opacity(0.05).edgesIgnoringSafeArea(.all))
        
    }
    
    private func fetchData() {
        userViewModel.getUsers()
    }
    
    private func onTapLoadView() {
        // tap to reload
        if userViewModel.isRequestFailed {
            userViewModel.isRequestFailed = false
            fetchData()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
APIService.swift
 
//
//  APIService.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import Foundation
import Combine

class APIService {
    static let shared = APIService()
    func getUsers(perPage: Int = 30, sinceId: Int? = nil) -> AnyPublisher<[User], Error> {
        var components = URLComponents(string: "https://api.github.com/users")!
        components.queryItems = [
            URLQueryItem(name: "per_page", value: "\(perPage)"),
            URLQueryItem(name: "since", value: (sinceId != nil) ? "\(sinceId!)" : nil)
        ]
        
        let request = URLRequest(url: components.url!, timeoutInterval: 5)
        return URLSession.shared.dataTaskPublisher(for: request)
            .map(\.data)
            .decode(type: [User].self, decoder: JSONDecoder())
            .eraseToAnyPublisher()
    }
}
LoaderView.swift
 
//
//  LoaderView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct LoaderView: View {
    let isFailed: Bool
    var body: some View {
        Text(isFailed ? "Failed. Tap to retry." : "Loading..")
            .foregroundColor(isFailed ? .red : .green)
            .padding()
            .font(.title)
    }
}

struct LoaderView_Previews: PreviewProvider {
    static var previews: some View {
        LoaderView(isFailed: false)
    }
}
User.swift
 
//
//  User.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import Foundation

struct User: Decodable, Identifiable {
    let id: Int
    let name: String
    let avatarUrl: String
    
    enum CodingKeys: String, CodingKey {
        case id
        case name = "login"
        case avatarUrl = "avatar_url"
    }
}
UserRow.swift
 
//
//  UserRow.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI
import SDWebImageSwiftUI //https://github.com/SDWebImage/SDWebImageSwiftUI.git

struct UserRow: View {
    let user: User
    @State var show = false
    
    var body: some View {
        VStack(spacing: 15){
            ZStack(alignment: Alignment(horizontal: .trailing, vertical: .top)) {
                
                Button {
                    show.toggle()
                } label: {
                    AnimatedImage(url: URL(string: user.avatarUrl)!)
                        .resizable()
                        .frame(height: 250)
                        .cornerRadius(15)
                }
                Button {
                } label: {
                                      
                    Image(systemName: "heart.fill")
                            .foregroundColor(.red)
                            .padding(.all,10)
                            .background(Color.white)
                            .clipShape(Circle())
                }
                .padding(.all,10)
            }
            Text(user.name)
                .fontWeight(.bold)
        }
        .sheet(isPresented: $show, content: {
            DetailsView(user: User(id: user.id, name: user.name, avatarUrl: user.avatarUrl))
        })
    }
}

struct UserRow_Previews: PreviewProvider {
    static var previews: some View {
        let mockUser = User(id: 1, name: "cairocoders", avatarUrl: "")
        UserRow(user: mockUser)
    }
}
UserViewModel.swift
 
//
//  UserViewModel.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import Foundation
import Combine

class UserViewModel: ObservableObject {
    @Published var users: [User] = []
    @Published var isRequestFailed = false
    private let pageLimit = 10
    private var currentLastId: Int? = nil
    private var cancellable: AnyCancellable?
    
    func getUsers() {
        cancellable = APIService.shared.getUsers(perPage: pageLimit, sinceId: currentLastId)
            .receive(on: DispatchQueue.main)
            .sink { completion in
                switch completion {
                case .failure(let error):
                    self.isRequestFailed = true
                    print(error)
                case .finished:
                    print("finished loading")
                }
            } receiveValue: { users in
                self.users.append(contentsOf: users)
                self.currentLastId = users.last?.id
            }

    }
}
DetailsView.swift
 
//
//  DetailsView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI
import SDWebImageSwiftUI

struct DetailsView: View {
    var user: User
    
    var body: some View {
        VStack {
            HStack {
                AnimatedImage(url: URL(string: user.avatarUrl)!)
                    .resizable()
                    .frame(width: 250, height: 250)
                    .cornerRadius(15)
            }
            
            HStack {
                Text("User Name :")
                Text(user.name)
            }
        }
    }
}

Tuesday, April 5, 2022

SwiftUI News API App - Load More Data List View Infinite Scroll

SwiftUI News API App - Load More Data List View Infinite Scroll

News API : https://newsapi.org/

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {

    var body: some View {
        NewsFeedView()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct NewsFeedView: View {
    @ObservedObject var newsFeed = NewsFeed()
    
    var body: some View {
        NavigationView {
            List(newsFeed) { (article: NewsListItem) in
                NavigationLink(destination: NewsListItemView(article: article)) {
                    NewsListItemListView(article: article)
                        .onAppear {
                            self.newsFeed.loadMoreArticles(currentItem: article)
                    }
                }
            }
        .navigationBarTitle("Apple News")
        }
    }
}

struct NewsListItemView: View {
    var article: NewsListItem
    
    var body: some View {
        VStack {
            UrlWebView(urlToDisplay: URL(string: article.url)!)
                .edgesIgnoringSafeArea(.all)
                .navigationBarTitle(article.title)
        }
    }
}

struct NewsListItemListView: View {
    var article: NewsListItem
    
    var body: some View {
        HStack {
            VStack(alignment: .leading) {
                Text("\(article.title)")
                    .font(.headline)
                Text("\(article.author ?? "No Author")")
                    .font(.subheadline)
            }
        }
    }
}
NewsFeedModels.swift
 
//
//  NewsFeedModels.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import Foundation

class NewsFeed: ObservableObject, RandomAccessCollection {
    typealias Element = NewsListItem
    
    @Published var newsListItems = [NewsListItem]()
    
    var startIndex: Int { newsListItems.startIndex }
    var endIndex: Int { newsListItems.endIndex }
    var loadStatus = LoadStatus.ready(nextPage: 1)
    
    var urlBase = "https://newsapi.org/v2/everything?q=apple&sortBy=popularity&apiKey=55c250f06e1144c29a3ec4d2530adbe5&language=en&page="
 
    init() {
        loadMoreArticles()
    }
    
    subscript(position: Int) -> NewsListItem {
        return newsListItems[position]
    }
    
    func loadMoreArticles(currentItem: NewsListItem? = nil) {
        
        if !shouldLoadMoreData(currentItem: currentItem) {
            return
        }
        guard case let .ready(page) = loadStatus else {
            return
        }
        loadStatus = .loading(page: page)
        let urlString = "\(urlBase)\(page)"
        
        let url = URL(string: urlString)!
        let task = URLSession.shared.dataTask(with: url, completionHandler: parseArticlesFromResponse(data:response:error:))
        task.resume()
    }
    
    func shouldLoadMoreData(currentItem: NewsListItem? = nil) -> Bool {
        guard let currentItem = currentItem else {
            return true
        }
        
        for n in (newsListItems.count - 4)...(newsListItems.count-1) {
            if n >= 0 && currentItem.uuid == newsListItems[n].uuid {
                return true
            }
        }
        return false
    }
    
    func parseArticlesFromResponse(data: Data?, response: URLResponse?, error: Error?) {
        guard error == nil else {
            print("Error: \(error!)")
            loadStatus = .parseError
            return
        }
        guard let data = data else {
            print("No data found")
            loadStatus = .parseError
            return
        }
        
        let newArticles = parseArticlesFromData(data: data)
        DispatchQueue.main.async {
            self.newsListItems.append(contentsOf: newArticles)
            if newArticles.count == 0 {
                self.loadStatus = .done
            } else {
                guard case let .loading(page) = self.loadStatus else {
                    fatalError("loadSatus is in a bad state")
                }
                self.loadStatus = .ready(nextPage: page + 1)
            }
        }
    }
    
    func parseArticlesFromData(data: Data) -> [NewsListItem] {
        var response: NewsApiResponse
        do {
            response = try JSONDecoder().decode(NewsApiResponse.self, from: data)
        } catch {
            print("Error parsing the JSON: \(error)")
            return []
        }
        
        if response.status != "ok" {
            print("Status is not ok: \(response.status)")
            return []
        }
        
        return response.articles ?? []
    }
    
    enum LoadStatus {
        case ready (nextPage: Int)
        case loading (page: Int)
        case parseError
        case done
    }
}

class NewsApiResponse: Codable {
    var status: String
    var articles: [NewsListItem]?
}

class NewsListItem: Identifiable, Codable {
    var uuid = UUID()
    
    var author: String?
    var title: String
    var url: String
    
    enum CodingKeys: String, CodingKey {
        case author, title, url
    }
}
UrlWebView.swift
 
//
//  UrlWebView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI
import WebKit

struct UrlWebView: UIViewRepresentable {
    typealias UIViewType = WKWebView
    
    var urlToDisplay: URL
    
    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        
        webView.load(URLRequest(url: urlToDisplay))
        
        return webView
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        
    }
}

Jquery Ajax Adding Multiple Rows with PHP OOP and Mysqli

Jquery Ajax Adding Multiple Rows with PHP OOP and Mysqli

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

Database Table

CREATE TABLE `multiplerow_members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `multiplerow_members` (`id`, `firstname`, `lastname`) VALUES
(1, 'Airi ', 'Sato'),
(2, 'Bourto', 'Usumaki');

ALTER TABLE `multiplerow_members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `multiplerow_members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>Jquery Ajax Adding Multiple Rows with PHP OOP and Mysqli</title>
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
	<div class="row">
		<div class="col-md-12">
			<h2>Jquery Ajax Adding Multiple Rows with PHP OOP and Mysqli</h2>
			<h2>Members Table</h2>
			<div id="table"></div>
		</div>
	</div>
	<div class="row">
		<div class="col-md-8">
			<h2>Add Form</h2>
			<form id="addForm">
				<hr>
				<div class="row">
					<div class="col-md-2">
						<label style="position:relative; top:7px;">Firstname:</label>
					</div>
					<div class="col-md-10">
						<input type="text" name="firstname[]" class="form-control">
					</div>
				</div>
				<div style="height:10px;"></div>
				<div class="row">
					<div class="col-md-2">
						<label style="position:relative; top:7px;">Lastname:</label>
					</div>
					<div class="col-md-10">
						<input type="text" name="lastname[]" class="form-control">
					</div>
				</div>
				<hr>
				<div id="newrow"></div>
				<div class="row">
					<div class="col-md-12">
						<button type="button" id="save" class="btn btn-primary"> Save</button>
						<button type="button" id="newbutton" class="btn btn-primary"> Add New</button>
					</div>
				</div>
			</form>
		</div>
	</div>
</div>
<script>
$(document).ready(function(){
	showTable();

	$('#newbutton').click(function(){
		$('#newrow').slideDown();
		var newrow = '<hr>';
			newrow = '<div class="row">';
   		 	newrow += '<div class="col-md-2"><label style="position:relative; top:7px;">Firstname:</label></div>';
   		 	newrow += '<div class="col-md-10"><input type="text" name="firstname[]" class="form-control"></div>';
   		 	newrow += '</div>';
   		 	newrow += '<div style="height:10px;"></div>';
   		 	newrow += '<div class="row">';
   		 	newrow += '<div class="col-md-2"><label style="position:relative; top:7px;">Lastname:</label></div>';
   		 	newrow += '<div class="col-md-10"><input type="text" name="lastname[]" class="form-control"></div>';
   		 	newrow += '</div>';
   		 	newrow += '<hr>';	 	 
   		$('#newrow').append(newrow);	
	});

	$('#save').click(function(){
		var addForm = $('#addForm').serialize();
		$.ajax({
			type: 'POST',
			url: 'add.php',
			data: addForm,
			success:function(data){
				if(data==''){
					showTable();
					$('#addForm')[0].reset();
					$('#newrow').slideUp();
					$('#newrow').empty();
				}
				else{
					showTable();
					$('#addForm')[0].reset();
					$('#newrow').slideUp();
					$('#newrow').empty();
					alert('Rows with empty field are not added');
				}
				
			}
		});
	});

});

function showTable(){
	$.ajax({
		type: 'POST',
		url: 'fetch.php',
		data:{
			fetch: 1,
		},
		success:function(data){
			$('#table').html(data);
		}
	});
}
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");
 
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
add.php
//add.php
<?php
	include('conn.php');
	if(isset($_POST['firstname'])){
		$firstname = $_POST["firstname"];
 		$lastname = $_POST["lastname"];

 		for($count = 0; $count<count($firstname); $count++){
  			$firstname_clean = mysqli_real_escape_string($conn, $firstname[$count]);
  			$lastname_clean = mysqli_real_escape_string($conn, $lastname[$count]);

  			if($firstname_clean != '' && $lastname_clean != ''){
				$conn->query("insert into multiplerow_members (firstname, lastname) values ('".$firstname_clean."', '".$lastname_clean."')");
			}
			else{
				echo "1";
			}
 		}
	}

?>
fetch.php
//fetch.php
<?php
	include('conn.php');
	if(isset($_POST['fetch'])){
		?>
			<table class="table table-bordered table-striped">
				<thead>
					<th>Firstname</th>
					<th>Lastname</th>
				</thead>
				<tbody>
					<?php
						include('conn.php');
						$query=$conn->query("select * from multiplerow_members");
						while($row=$query->fetch_array()){
							?>
							<tr>
								<td><?php echo $row['firstname']; ?></td>
								<td><?php echo $row['lastname']; ?></td>
							</tr>
							<?php
						}
					?>
				</tbody>
			</table>
		<?php
	}

?>

Monday, April 4, 2022

jQuery Preview Multiple Images

jQuery Preview Multiple Images

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

index.html
//index.html
<!DOCTYPE html>
<html>
<head>
	<title>jQuery Preview Multiple Images</title>
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
	<style>
		.hidden{
			display:none;
		}
    	#preview{
    		margin-top:50px;
    	}    	
		#preview img {
    		margin:10px;
    	}
	</style>
</head>
<body>
<div class="container">
	<div class="row">
		<h2><center>jQuery Preview Multiple Images </center></h2>
		<input type="file" name="file" id="file" class="hidden" multiple>
		<center><button type="button" class="btn btn-primary" id="filebutton"><span id="filetext">Select File</span></button></center>
		<div id="preview"></div>	
	</div>
</div>
<script>
$(document).ready(function(){
	$('#filebutton').click(function(){
		$('#file').click();
	});

	$('#file').change(function(){

		var name = $(this).val().split('\\').pop();
		var file = $(this)[0].files;
		if(name != ''){
			if(file.length >=2){
				$('#filetext').html(file.length + ' files ready to upload');
			}
			else{
				$('#filetext').html(name);
			}
		}
	});

	$('#file').on("change", previewImages);
});

function previewImages() {

  var $preview = $('#preview').empty();
  if (this.files) $.each(this.files, readAndPreview);

  function readAndPreview(i, file) {
    
    if (!/\.(jpe?g|png|gif)$/i.test(file.name)){
      return alert(file.name +" is not an image");
    } // else...
    
    var reader = new FileReader();

    $(reader).on("load", function() {
      $preview.append($("<img>", {src:this.result, height:200}));
    });

    reader.readAsDataURL(file);
    
  }

}
</script>
</body>
</html>

Sunday, April 3, 2022

Python Django How To Use DataTables with Insert Data Jquery Ajax

Python Django How To Use DataTables with Insert Data Jquery Ajax

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

https://datatables.net/
DataTables is a powerful jQuery plugin for creating table listings and adding interactions to them. It provides searching, sorting and pagination without any configuration. 


testdev/urls.py
 
//testdev/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('', views.index, name='index'),
	path('insert', views.insert, name='insert'),
    path('admin/', admin.site.urls),
]
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render, redirect
from .models import Member

# Create your views here.
def index(request):
    all_members = Member.objects.all()
    return render(request, 'datatables/index.html', {'all_members': all_members})

def insert(request):
    member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'], address=request.POST['address'])
    member.save()
    return redirect('/')
myapp/models.py
 
//myapp/models.py
from django.db import models

# Create your models here.
class Member(models.Model):
    firstname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)
    address = models.CharField(max_length=50)
 
    def __str__(self):
        return self.firstname + " " + self.lastname
myapp/templates/datatables/index.html
 
//myapp/templates/datatables/index.html
{% extends 'datatables/base.html' %}
{% block body %}
<p>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addnewmember" style="width:300px;">
  Add New
</button>
</p>
<!-- Modal -->
<div class="modal fade" id="addnewmember" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add New</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
		<form method="POST">
			{% csrf_token %}
			<div class="mb-3">
				<label>Firstname</label>
				   <input type="text" id="firstname" class="form-control"/>
			</div>        
			<div class="mb-3">
				<label>Lastname</label>
				<input type="text" id="lastname" class="form-control"/>
			</div>
			<div class="mb-3">
				<label>Address</label>
				<input type="text" id="address" class="form-control"/>
			</div>
		
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="submit">Submit</button>
      </div>
	  </form>
    </div>
  </div>
</div>

<hr style="border-top:1px solid #000; clear:both;"/>
<table id = "table" class = "table table-bordered">
    <thead class="alert-warning">
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Address</th>
        </tr>
    </thead>
    <tbody>
        {% for member in all_members %}
        <tr>
            <td>{{ member.firstname }}</td>
            <td>{{ member.lastname }}</td>
            <td>{{ member.address  }}</td>
        </tr>
        {% endfor %}
    </tbody>
</table>
{% endblock %}
myapp/templates/datatables/base.html
 
//myapp/templates/datatables/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Python Django How To Use DataTables with Insert Data Jquery Ajax</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
	<link rel = "stylesheet" type = "text/css" href = "https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
<div class="container">
    <div class="row">
        <p><h3 class="text-primary">Python Django How To Use DataTables with Insert Data Jquery Ajax</h3></p>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block body %}
 
        {% endblock %}
    </div>
</div>    
</body>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script src = "https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
    $('#table').DataTable();
	
    $('#submit').on('click', function(){
        $firstname = $('#firstname').val();
        $lastname = $('#lastname').val();
        $address = $('#address').val();
 
        if($firstname == "" || $lastname == "" || $address == ""){
            alert("Please complete field");
        }else{
            $.ajax({
                type: "POST",
                url: "insert",
                data:{
                    firstname: $firstname,
                    lastname: $lastname,
                    address: $address,
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
                },
                success: function(){
                    alert('Save Data');
                    $('#firstname').val('');
                    $('#lastname').val('');
                    $('#address').val('');
                    window.location = "/";
                }
            });
        }
    });
});
</script>
</html>
Register App myapp
devtest/settings.py
 
//devtest/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]

migration
C:\my_project_django\testdev>python manage.py makemigrations
C:\my_project_django\testdev>python manage.py migrate

Saturday, April 2, 2022

Dependent Dropdown with Loading using Jquery Ajax and PHP Mysqli

Dependent Dropdown with Loading using Jquery Ajax and PHP Mysqli

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

Database Table

CREATE TABLE `carbrands` (
  `brand_id` int(11) NOT NULL,
  `brand_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `carbrands` (`brand_id`, `brand_name`) VALUES
(1, 'Toyota'),
(2, 'Honda'),
(3, 'Suzuki'),
(4, 'Mitsubishi'),
(5, 'Hyundai');

ALTER TABLE `carbrands`
  ADD PRIMARY KEY (`brand_id`);

ALTER TABLE `carbrands`
  MODIFY `brand_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
  
CREATE TABLE `carmodels` (
  `model_id` int(11) NOT NULL,
  `brand_id` int(11) NOT NULL,
  `car_models` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `carmodels` (`model_id`, `brand_id`, `car_models`) VALUES
(1, 1, 'Toyota Corolla'),
(2, 2, 'Toyota Camry'),
(3, 1, 'Toyota Yaris'),
(4, 1, 'Toyota Sienna'),
(5, 1, 'Toyota RAV4'),
(6, 1, 'Toyota Highlander'),
(7, 2, 'Honda HR-V'),
(8, 2, 'Honda Odyssey'),
(9, 3, 'Swift'),
(10, 3, 'Celerio'),
(11, 3, 'Ertiga'),
(12, 3, 'Vitara'),
(13, 4, 'Mirage'),
(14, 4, 'Mirage G4'),
(15, 4, 'Xpander Cross'),
(16, 4, 'Montero Sport'),
(17, 4, 'Strada Athlete'),
(18, 5, 'Reina '),
(19, 5, 'Accent'),
(20, 5, 'Elantra'),
(21, 5, 'Tucson');

ALTER TABLE `carmodels`
  ADD PRIMARY KEY (`model_id`),
  ADD KEY `industry_id` (`brand_id`);

ALTER TABLE `carmodels`
  MODIFY `model_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;

index.php
//index.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dependent Dropdown with Loading using Jquery Ajax and PHP Mysqli</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />   
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script> 
</head>
<body>
<?php
include('conn.php');
?>
<div class="container">
 <h3 class="mt-4 text-center text-secondary">Dependent Dropdown with Loading using Jquery Ajax and PHP Mysqli</h3>
  <div class="row">
    <div class="col-sm-4">

      <h5 class="mt-4">Car Brand Name</h5>
       <select name="carbrand" id="carbrand" class="form-select">
        <?php 
              $sql = "SELECT * FROM carbrands";
              $query = mysqli_query($conn,$sql);
              while($row=mysqli_fetch_assoc($query))
              {
                echo '<option value="'.$row['brand_id'].'">'.$row["brand_name"].'</option>';
              }
        ?>
       </select>
	</div>
    <div class="col-sm-4">
      <h5 class="mt-4 ">Car Model</h5>
        <p id="loading" style="display:none">
           <img src="img/loader.gif"><span class="sr-only">Loading...</span>
        </p>
        <select  class="form-select"  name="select" id="show"  style="display:none;"></select>
	</div>
</div>
</div>
<script>
  $(document).ready(function(){
    $('#carbrand').change(function(){
      var Stdid = $('#carbrand').val(); 
       $.ajax({
          url:'fetch.php',
          type:'POST',
          data:{id:Stdid},
          success:function(response)
          {
            $('#loading').css('display','block');
            setTimeout(function()
            { 
                $('#show').html(response);
                $('#show').show();
                $('#loading').css('display','none');
            },3000);
          }
       });
    });
  });
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
fetch.php
//fetch.php
<?php
  include('conn.php');

  $id = $_POST['id'];
  $sql = "SELECT * FROM carmodels WHERE brand_id= $id ";
  $result = mysqli_query($conn,$sql);

  $out='';
  while($row = mysqli_fetch_assoc($result)) 
  {   
     $out .=  '<option>'.$row['car_models'].'</option>'; 
  }
   echo $out;
?>

Jquery Ajax Dependent Dropdown Select with PHP Mysqli

Jquery Ajax Dependent Dropdown Select with PHP Mysqli

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

Database Table

CREATE TABLE `carbrands` (
  `brand_id` int(11) NOT NULL,
  `brand_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `carbrands` (`brand_id`, `brand_name`) VALUES
(1, 'Toyota'),
(2, 'Honda'),
(3, 'Suzuki'),
(4, 'Mitsubishi'),
(5, 'Hyundai');

ALTER TABLE `carbrands`
  ADD PRIMARY KEY (`brand_id`);

ALTER TABLE `carbrands`
  MODIFY `brand_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
  
CREATE TABLE `carmodels` (
  `model_id` int(11) NOT NULL,
  `brand_id` int(11) NOT NULL,
  `car_models` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `carmodels` (`model_id`, `brand_id`, `car_models`) VALUES
(1, 1, 'Toyota Corolla'),
(2, 2, 'Toyota Camry'),
(3, 1, 'Toyota Yaris'),
(4, 1, 'Toyota Sienna'),
(5, 1, 'Toyota RAV4'),
(6, 1, 'Toyota Highlander'),
(7, 2, 'Honda HR-V'),
(8, 2, 'Honda Odyssey'),
(9, 3, 'Swift'),
(10, 3, 'Celerio'),
(11, 3, 'Ertiga'),
(12, 3, 'Vitara'),
(13, 4, 'Mirage'),
(14, 4, 'Mirage G4'),
(15, 4, 'Xpander Cross'),
(16, 4, 'Montero Sport'),
(17, 4, 'Strada Athlete'),
(18, 5, 'Reina '),
(19, 5, 'Accent'),
(20, 5, 'Elantra'),
(21, 5, 'Tucson');

ALTER TABLE `carmodels`
  ADD PRIMARY KEY (`model_id`),
  ADD KEY `industry_id` (`brand_id`);

ALTER TABLE `carmodels`
  MODIFY `model_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;


index.php
//index.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Jquery Ajax Dependent Dropdown Select with PHP Mysqli</title>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />   
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script> 
</head>
<body>
<?php
include('conn.php');
?>
 <div class="container mt-4">
 <h4 class="text-center">Jquery Ajax Dependent Dropdown Select with PHP Mysqli</h4><br>
   <div class="row">
    <div class="col-sm-4">
      <h6>Car Brand Name</h6>
        <select class="form-select" name="select" id="selectID">
        <option>Select Option</option>

        <?php $sql = "SELECT * FROM carbrands";
            $result = mysqli_query($conn,$sql);
            while($row = mysqli_fetch_assoc($result)) {?>
            <option value="<?php echo $row['brand_id'] ?>"><?php echo $row['brand_name'] ?></option>
            <?php }?>

        </select>
     </div> 

     <div class="col-sm-4">  
     <h6>Car Model</h6>
      <select  class="form-select"  name="select" id="show"></select>
    </div>
   
   </div>
 </div>  
<script>
  $(document).ready(function(){
     $('#selectID').change(function(){
      var Stdid = $('#selectID').val(); 

      $.ajax({
        type: 'POST',
        url: 'fetch.php',
        data: {id:Stdid},  
        success: function(data)  
         {
            $('#show').html(data);
         }
        });
     });
  });
</script> 
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
fetch.php
//fetch.php
<?php
  include('conn.php');

  $id = $_POST['id'];
  $sql = "SELECT * FROM carmodels WHERE brand_id= $id ";
  $result = mysqli_query($conn,$sql);

  $out='';
  while($row = mysqli_fetch_assoc($result)) 
  {   
     $out .=  '<option>'.$row['car_models'].'</option>'; 
  }
   echo $out;
?>

Load More Data using Jquery Ajax with PHP MySQLi

Load More Data using Jquery Ajax with PHP MySQLi


Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

CREATE TABLE `country` (
  `id` int(6) NOT NULL,
  `country` varchar(250) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `country` (`id`, `country`) VALUES
(1, 'Afghanistan'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(5, 'American Samoa'),
(6, 'Andorra'),
(7, 'Angola'),
(8, 'Anguilla'),
(9, 'Antarctica'),
(10, 'Antigua and Barbuda'),
(11, 'Argentina'),
(12, 'Armenia'),
(13, 'Aruba'),
(14, 'Australia'),
(15, 'Austria'),
(16, 'Azerbaijan'),
(17, 'Bahamas'),
(18, 'Bahrain'),
(19, 'Bangladesh'),
(20, 'Barbados');

ALTER TABLE `country`
  ADD PRIMARY KEY (`id`);
  
ALTER TABLE `country`
  MODIFY `id` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;


index.php
//index.php
<!DOCTYPE html>  
<html>  
<head>  
      <title>Load More Data using Jquery Ajax with PHP MySQLi</title>  
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />   
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>  
</head>  
<body>  
      <div class="container">   
        <div class="row">
              <h2 align="center">Load More Data using Jquery Ajax with PHP MySQLi</h2>
              <div id="loadtable">  
                  <?php
                    $lastid='';
                    include('conn.php');
                    $query=mysqli_query($conn,"select * from country order by id asc limit 5");
                    while($row=mysqli_fetch_array($query)){
                        ?>
                        <div class="row">
                            <div class="col-lg-12">
                                <div class="btn btn-success" style="margin:10px;width:50%;"><?php echo $row['country']; ?></div>
                            </div>
                        </div>
                        <?php
                      $lastid=$row['id'];
                    }

                  ?>
                  <div id="remove">
                  <div class="row">
                      <div class="col-lg-12">
                      <button type="button" name="loadmore" id="loadmore" data-id="<?php echo $lastid; ?>" class="btn btn-primary">See More</button>
                      </div>
                  </div>
                  </div>  
                </div>  
          </div>  
      </div>

<script>
$(document).ready(function(){  
      $(document).on('click', '#loadmore', function(){  
           var lastid = $(this).data('id');  
           $('#loadmore').html('Loading...');  
           $.ajax({  
                url:"load_data.php",  
                method:"POST",  
                data:{
                    lastid:lastid,
                },  
                dataType:"text",  
                success:function(data)  
                {  
                     if(data != '')  
                     {  
                          $('#remove').remove();  
                          $('#loadtable').append(data);  
                     }  
                     else  
                     {  
                          $('#loadmore').html('No more data to show');  
                     }  
                }  
           });  
      });  
 }); 
</script>  
</body>  
</html>  
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
load_data.php
//load_data.php
<?php  
     sleep(1);  
     include('conn.php');
     if(isset($_POST['lastid'])){
          $lastid=$_POST['lastid'];
          $query=mysqli_query($conn,"select * from country where id > '$lastid' order by id asc limit 5");
  
          if(mysqli_num_rows($query) > 0){  
          while($row = mysqli_fetch_array($query)){  
               ?>
                    <div class="row">
                         <div class="col-lg-12">
                              <div class="btn btn-success" style="margin:10px;width:50%;"><?php echo $row['country']; ?></div>
                         </div>
                    </div>
               <?php
               $lastid=$row['id'];
          }
          ?>
          <div id="remove"> 
          <div id="remove_row" class="row">
               <div class="col-lg-12">
                    <button type="button" name="loadmore" id="loadmore" data-id="<?php echo $lastid; ?>" class="btn btn-primary">See More</button>
               </div>
          </div>
          </div> 
          <?php 
          }  
     }
?>

Monday, March 28, 2022

Submit Form using Jquey AJAX with PHP MySQLi

Submit Form using Jquey AJAX with PHP MySQLi

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

Database Table

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>Submit Form using Jquey AJAX with PHP MySQLi</title>
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
	<div class="card card-body bg-light">
		<div class="row">
			<div class="col-lg-12">
				<h2><center>Submit Form using Jquey AJAX with PHP MySQLi</center></h2>
			</div>
		</div>
		<form id="form">
		<div class="row">
			<div class="mb-3">
				<label class="form-label">Firstname:</label>
				<input type="text" name="firstname" class="form-control">
			</div>
		</div>
		<div class="row">
			<div class="mb-3">
				<label class="form-label">Lastname:</label>
				<input type="text" name="lastname" class="form-control">
			</div>
		</div>
		<div class="row">
			<div class="mb-3">
				<label class="form-label">Address:</label>
				<input type="text" name="address" class="form-control">
			</div>
		</div>
		</form>
		<div class="row">
			<div class="col-lg-12">
				<button type="button" class="btn btn-primary pull-right" id="submit">Submit</button>
			</div>
		</div>
	</div>
	<div class="row" style="margin-top:20px;">
		<div id="table">
		</div>
	</div>
</div>
<script>
$(document).ready(function(){

	showTable();

	$('#submit').click(function(){
		var form=$('#form').serialize();
		$.ajax({
			url:"add.php",
			method:"POST",
			data:form,
			success:function(){
				showTable();
				$('#form')[0].reset();
			} 
		});
	});
});

function showTable(){
	$.ajax({
		url:"fetch.php",
		method:"POST",
		data:{
			fetch: 1,
		},
		success:function(data){
			$('#table').html(data);
		}
	});
}
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
 
?>
fetch.php
//fetch.php
<?php
	include('conn.php');
	if(isset($_POST['fetch'])){
		?>
		<table class="table table-bordered table-striped">
			<thead>
				<th>Firstname</th>
				<th>Lastname</th>
				<th>Address</th>
			</thead>
			<tbody>
				<?php
					$query=mysqli_query($conn,"select * from members order by id desc");
					while($row=mysqli_fetch_array($query)){
					?>
					<tr>
						<td><?php echo $row['firstname']; ?></td>
						<td><?php echo $row['lastname']; ?></td>
						<td><?php echo $row['address']; ?></td>
					</tr>
					<?php
					}
				?>
			</tbody>
		</table>
		<?php	
	}
?>
add.php
//add.php
<?php 
	include('conn.php');
	if(isset($_POST['firstname'])){
		$firstname=$_POST['firstname'];
		$lastname=$_POST['lastname'];
		$address=$_POST['address'];

		mysqli_query($conn,"insert into members (firstname, lastname, address) values ('$firstname', '$lastname', '$address')");
	}
?>

Related Post