Tuesday, 30 April 2019

How to Append Database Rows to HTML Table using Ajax with PHP



This is one more post on PHP with Ajax and in this post you can find how to Append Last Inserted Data to HTML table by using Ajax with PHP script. So, we do not want to fetch whole table data from mysql database and converted into HTML table and display on web page. In simple terms, if you have use ajax with PHP, then what happen at the time of inserting of data using Ajax with PHP, in PHP script you have first run insert query command and then after you have fetch whole table data from Mysql table and convert into HTML table and send back to Ajax request.

But If you have use Ajax then why you have fetch whole table data again and again on every insert of data. But append last inserted data to existing table. So, when your script has done inserting of data, then last inserting details will be send to Ajax request in JSON format and in Ajax success function that json data will be converted into table row format and by using prepend() method we can append into HTML table. So User will fill lasted submitted data has been store under database and from database that data has been display on web in HTML table format.

Here we have do simple process of Insert data into Mysql table using PHP with Ajax and here by using jQuery which has build table row from Ajax response which has been received in JSON format. So, jQuery has append Ajax result into existing table without refresh of web page. If you have not know how to append ajax return data to HTML table then your doubt will be clear from this post. You can append data from start of the table by using jQuery prepend() method and if you want to append at the end of table then by using jQuery append() method. Below you can find complete source code and online demo also.







Source Code


index.php



ect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

$query = "SELECT * FROM tbl_sample ORDER BY id DESC";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

?>

<html>
 <head>
  <title>How to Use Ajax PHP to Append Last Inserted Data to HTML Tables | Using AJAX to append database rows to HTML tables</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
 </head>
 <body>
  <div class="container">
   <br />
   <br />
   <h2 align="center">How to Use Ajax PHP to Append Last Inserted Data to HTML Tables</h2><br />
   <h3 align="center">Add Details</h3>
   <br />
   <form method="post" id="add_details">
    <div class="form-group">
     <label>First Name</label>
     <input type="text" name="first_name" class="form-control" required />
    </div>
    <div class="form-group">
     <label>Last Name</label>
     <input type="text" name="last_name" class="form-control" required />
    </div>
    <div class="form-group">
     <input type="submit" name="add" id="add" class="btn btn-success" value="Add" />
    </div>
   </form>
   <br />
   <h3 align="center">View Details</h3>
   <br />
   <table class="table table-striped table-bordered">
    <thead>
     <tr>
      <th>First Name</th>
      <th>Last Name</th>
     </tr>
    </thead>
    <tbody id="table_data">
    <?php
    foreach($result as $row)
    {
     echo '
     <tr>
      <td>'.$row["first_name"].'</td>
      <td>'.$row["last_name"].'</td>
     </tr>
     ';
    }
    ?>
    </tbody>
   </table>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 $('#add_details').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"insert.php",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   beforeSend:function(){
    $('#add').attr('disabled', 'disabled');
   },
   success:function(data){
    $('#add').attr('disabled', false);
    if(data.first_name)
    {
     var html = '<tr>';
     html += '<td>'+data.first_name+'</td>';
     html += '<td>'+data.last_name+'</td></tr>';
     $('#table_data').prepend(html);
     $('#add_details')[0].reset();
    }
   }
  })
 });
 
});
</script>


insert.php



<?php

//insert.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

$data = array(
 ':first_name'  => $_POST["first_name"],
 ':last_name'  => $_POST["last_name"]
); 

$query = "
 INSERT INTO tbl_sample 
(first_name, last_name) 
VALUES (:first_name, :last_name)
";

$statement = $connect->prepare($query);

if($statement->execute($data))
{
 $output = array(
  'first_name' => $_POST['first_name'],
  'last_name'  => $_POST['last_name']
 );

 echo json_encode($output);
}

?>





Saturday, 27 April 2019

Ajax Form Validation in Codeigniter with JSON



If you not know how to validate form data by using Codeigniter Form validation library by using Ajax and receive response in JSON data type. In this post you can find Form validation in Codeignter by using Ajax jQuery and JSON. For learn Codeigniter Form Validation library with Ajax, here we will make codeigniter ajax contact form for learn this topic.

We have already learn many thing in Codeigniter framework with Ajax. In this post we have share interesting topic on Codeigniter with Ajax and here you can find how to create Ajax jQuery form validation in Codeigniter framework. With help of Codeigniter Form validation library with Ajax, we will received success or error message in JSON format.

Every programmer know validation is a very important part of any web based application or any type of Software process. Because in every web application you can find form like login form, registration form, contact us form comment form etc, so we want to validate form data, if we have not validate form data then it is very dangerous for our web application. If you have use Codeigniter framework for your web based application then Codeigniter has rich form validation library for validate form data, which set server side validation. But server side form data validation has refresh page on every form submission. So, We want to prevent to refresh form, we have to use Ajax with Codeigniter form validation library. Which has been send ajax request to Codeigniter method which will perform validation rules on form data by using Form Validation library. If there is any validation error occur then by using form_error() method it will fetch validation error and store under array and send to back to ajax request in JSON format.

So, Form submission process will be done without refresh of web page. Here you can also find how to submit form in codeigniter by using Ajax without refresh of web page. For learn this topic here we will make contact form with field like name, email address, subject and message. This contact form data will be send to Codeigniter method by using Ajax. In Codeigiter method it will perform different validation rules like required field validation, email format validation by using codeigniter form validation library. And after success of validation rules then it will send response to ajax in json format. Below you can find complete source code of Codeigniter Ajax Form validation.





Source Code


Form_validation.php (Controllers)



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Form_validation extends CI_Controller {

 function index()
 {
  $this->load->view('form_validation');
 }

 function validation()
 {
  $this->load->library('form_validation');
  $this->form_validation->set_rules('name', 'Name', 'required');
  $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
  $this->form_validation->set_rules('subject', 'Subject', 'required');
  $this->form_validation->set_rules('message', 'Message', 'required');
  if($this->form_validation->run())
  {
   $array = array(
    'success' => '<div class="alert alert-success">Thank you for Contact Us</div>'
   );
  }
  else
  {
   $array = array(
    'error'   => true,
    'name_error' => form_error('name'),
    'email_error' => form_error('email'),
    'subject_error' => form_error('subject'),
    'message_error' => form_error('message')
   );
  }

  echo json_encode($array);
 }

}

?>


form_validation.php (Views)



<html>
<head>
    <title>Codeigniter Form Validation using Ajax JSON</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>    
</head>
<body>
 <div class="container">
  <br />
  <h3 align="center">Codeigniter Form Validation using Ajax JSON</h3>
  <br />
  <div class="row">
   <div class="col-md-4">

   </div>
   <div class="col-md-4">
    <span id="success_message"></span>
    <form method="post" id="contact_form">
     <div class="form-group">
      <input type="text" name="name" id="name" class="form-control" placeholder="Name" />
      <span id="name_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <input type="text" name="email" id="email" class="form-control" placeholder="Email Address" />
      <span id="email_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <input type="text" name="subject" id="subject" class="form-control" placeholder="Subject">
      <span id="subject_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <textarea name="message" id="message" class="form-control" placeholder="Message" rows="6"></textarea>
      <span id="message_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <input type="submit" name="contact" id="contact" class="btn btn-info" value="Contact Us">
     </div>
    </form>
   </div>
   <div class="col-md-4"></div>
  </div>
 </div>
</body>
</html>
<script>
$(document).ready(function(){

 $('#contact_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"<?php echo base_url(); ?>form_validation/validation",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   beforeSend:function(){
    $('#contact').attr('disabled', 'disabled');
   },
   success:function(data)
   {
    if(data.error)
    {
     if(data.name_error != '')
     {
      $('#name_error').html(data.name_error);
     }
     else
     {
      $('#name_error').html('');
     }
     if(data.email_error != '')
     {
      $('#email_error').html(data.email_error);
     }
     else
     {
      $('#email_error').html('');
     }
     if(data.subject_error != '')
     {
      $('#subject_error').html(data.subject_error);
     }
     else
     {
      $('#subject_error').html('');
     }
     if(data.message_error != '')
     {
      $('#message_error').html(data.message_error);
     }
     else
     {
      $('#message_error').html('');
     }
    }
    if(data.success)
    {
     $('#success_message').html(data.success);
     $('#name_error').html('');
     $('#email_error').html('');
     $('#subject_error').html('');
     $('#message_error').html('');
     $('#contact_form')[0].reset();
    }
    $('#contact').attr('disabled', false);
   }
  })
 });

});
</script>





Wednesday, 24 April 2019

Login Registration System with Email Verification in Laravel 5.8



Do you know you can make complete login registration system in Laravel 5.8 with email verification in single artisan command run. If you not know then this post will help you to learn Laravel login authentication and register with step by step guide from scratch. Because Laravel 5.8 has default Login Registration authentication system, so you can make complete login register system in Laravel 5.8 in single run of artisan command run. Here we will discuss step by step process to build Login authentication and register system in Larave 5.8 application. You don't have write any line of code for make login and register system in Laravel 5.8 application. Last release of Laravel 5.8 introduce new features with improvements. So, by using that new features we will make login and register system by using one artisan command like php artisan make:auth. It will create default controllers file, views blade file and set routes for Login and register system.

In this login registration system here we will also covered email verification feature also. So, here we will learn how to verify email address after user has done registration in Laravel 5.8 application. For email verification here we will use new Laravel feature like MustEmailVerify contracts. When user will verify email and it will authenticate and redirect to Laravel user dashboard. If User register and he has not verify his email address then user will not access dashboard of Laravel 5.8 application. In Laravel 5.8 email verification process is very simple and easy to use. We can also modify default Laravel email template and we can create custom email template of email verification, forget password and password reset. If you have use Laravel default Login Registration system then it will reduce your most of time of development.



Install Laravel 5.8


First we want to install Laravel 5.8 fresh set up in out system. For this we have to open terminal and write below command.


composer create-project --prefer-dist laravel/laravel firstApp


Configure .env file


Once you have done install Laravel 5.8 application, in next step we want to configuare .env file for Mysql configuration and email sending configuration.


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



MAIL_DRIVER=smtp
MAIL_HOST=smtpout.secureserver.net
MAIL_PORT=80
MAIL_USERNAME=xxxxx
MAIL_PASSWORD=xxxxx
MAIL_ENCRYPTION=null





Generate Laravel 5.8 Application Key


After .env configuration completed then we have to generate application. For this we have to go command prompt and write following command for genrate laravel application key.


php artisan key:generate


Laravel 5.8 Database Migration


For make Login Register system we have to make User table in Mysql database. Here we will make User table from this Laravel 5.8 application by migrating database. But before migrating database by using command. First we have to open app/providers/AppServiceProvider.php and add two line of code under boot method.


<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }
}

?>


After this we have to go to command prompt and write following command, it will automatic create tables in mysql database and it will also create migration file.


php artisan migrate


After migrating of database, User.php file will be make under app folder. So, we have to open that file and add MustVerifyEmail contracts under the constuctor method. It is for enable email verification.

app/User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable  = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

?>


Laravel 5.8 Authentication


Here we will use Laravel 5.8 default Login Register system by using Laravel 5.8 authentication. For this we have to write following command in command prompt. This command will create controllers, routes and views files for Laravel authentication and registration.


php artisan make:auth


Add Route


For Email Verification, we need to add route under routes/web.php file.


<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Auth::routes(['verify' => true]); 

Route::get('/home', 'HomeController@index')->name('home');


Add middleware in Controller


After this we need to add middleware in Controller constuctor. For this we have to open app/Http/Controllers/HomeController.php file and add $this->middleware([‘auth’, ‘verified’]); this line under constructor.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'verified']);
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }
}

?>


Run Laravel 5.8 application


For run Laravel 5.8 application, we have to go to command prompt and write following command. It will start Laravel 5.8 application and return base url of your Laravel 5.8 application.


php artisan serve


This is complete step by step process for build User Login Register System in Laravel 5.8 application by using default Laravel 5.8 authentication.

Sunday, 21 April 2019

How to Join Multiple Table in Laravel 5.8



This is one more tutorial on Laravel 5.8 framework and in this post you can find how to join multiple table in Laravel 5.8 framework. Here we will take example of fetch data from two or more table by using inner join in Laravel 5.8 and display on web page. If you are looking for learn how to make inner join with multiple table in Laravel 5.8 then this tutorial will help you because here we have take simple example for fetch data from multiple table from scratch.

Join Table means returns the records or rows which are present in both table, for this there is at least one table column match between two table. So, this type of join we have to make in Laravel 5.8 framework. There is major benefits of join of multiple table is that in one query execution you can fetch data from multiple table. Below you can find source of Laravel 5.8 join multiple table by using inner join.







JoinTableController.php


app/Http/Controllers/>JoinTableController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class JoinTableController extends Controller
{
    function index()
    {
     $data = DB::table('city')
       ->join('state', 'state.state_id', '=', 'city.state_id')
       ->join('country', 'country.country_id', '=', 'state.country_id')
       ->select('country.country_name', 'state.state_name', 'city.city_name')
       ->get();
     return view('join_table', compact('data'));
    }
}
?>


join_table.blade.php


resources/views/join_table.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - Join Multiple Table</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 - Join Multiple Table</h3>
     <br />
   <div class="table-responsive">
    <table class="table table-bordered table-striped">
           <thead>
            <tr>
                <th>Country</th>
                <th>State</th>
                <th>City</th>
            </tr>
           </thead>
           <tbody>
           @foreach($data as $row)
            <tr>
             <td>{{ $row->country_name }}</td>
             <td>{{ $row->state_name }}</td>
             <td>{{ $row->city_name }}</td>
            </tr>
           @endforeach
           </tbody>
       </table>
   </div>
  </div>
 </body>
</html>


web.php


routes/web.php

Route::get('join-table', 'JoinTableController@index');


Thursday, 18 April 2019

Live CSV File Data Editing and Importing in PHP using Ajax jQuery



This is very interesting post, in which we have covered topic like Uploading CSV file data and then after before import into Mysql table we can edit CSV file data on web page by using jquery Ajax with PHP. Now what are benefits of this feature, because suppose we want to edit CSV file data then we can directly edit into CSV file and then after we can proceed for importing. But suppose you don't know there is some spelling error or any information is wrong in CSV file data and you have start upload CSV file for import data then you cannot stop importing process and wrong data will be directly import into Mysql table. But in this feature when you have upload CSV file for importing into Mysql table then on web page first it will display all CSV file data on web page in table format and you can edit any table column data before importing. So you after uploading file you can check all CSV file data on web page and if there is any wrong data is found then you can edit them and then after you can import into Database by using PHP with Ajax jQuery.

In Current Web Development, there are new and new innovation has been developed for reducing error. So, this feature also is one innovation for importing data through CSV file. Because here data has been verified by two times and if any wrong information has been then we can Live Edit that CSV file data before importing. We all know CSV file format is widely used for import and export of data from any web application. Then if you have build any enterprise level web application and in that you have import data from CSV file then this feature will reduce human work, because we can edit CSV file data after uploading CSV file and before importing into database. So, this feature will reduce importing of wrong data into Database. So, here we have make one more tutorial on Live CSV file data editing and then after importing in Mysql Database by using PHP with Ajax jQuery.






index.php


This is then main file of this tutorial, In this find HTML code and jQuery Ajax code. In HTML code we have make one form in which we have define on file tag for select CSV file and upload button for send CSV file to server. And in jQuery Ajax code you can see below we have write jQuery code on two button click event.

First button click event will send selected CSV file to fetch.php file. For send file data to server, here we have use new FormData() object. After success of Ajax request it will received data in JSON format, and that data will be converted into HTML table format and display on web page. With table it will also make import button with id import_data will also make for import data into Mysql table. In student name table column has attribute like class="student_name" and student phone table column has attribute like class="student_phone". So, this column data will be fetch from jQuery code, and this two column will be editable by using contenteditable attribute.

In second jQuery click event has write on Import button, so when we have click on import button then this code will execute. In this first it has fetch data from attribute class and store under local variable in array format. Then after that local variable value will be send to PHP script by using Ajax request. Ajax request will send request to import.php file for import data into Database. After successfully importing of data it will display success message on web page.





<!DOCTYPE html>
<html>
 <head>
  <title>CSV File Editing and Importing in PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <style>
  .box
  {
   max-width:600px;
   width:100%;
   margin: 0 auto;;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">CSV File Editing and Importing in PHP</h3>
   <br />
   <form id="upload_csv" method="post" enctype="multipart/form-data">
    <div class="col-md-3">
     <br />
     <label>Select CSV File</label>
    </div>  
                <div class="col-md-4">  
                    <input type="file" name="csv_file" id="csv_file" accept=".csv" style="margin-top:15px;" />
                </div>  
                <div class="col-md-5">  
                    <input type="submit" name="upload" id="upload" value="Upload" style="margin-top:10px;" class="btn btn-info" />
                </div>  
                <div style="clear:both"></div>
   </form>
   <br />
   <br />
   <div id="csv_file_data"></div>
   
  </div>
 </body>
</html>

<script>

$(document).ready(function(){
 $('#upload_csv').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"fetch.php",
   method:"POST",
   data:new FormData(this),
   dataType:'json',
   contentType:false,
   cache:false,
   processData:false,
   success:function(data)
   {
    var html = '<table class="table table-striped table-bordered">';
    if(data.column)
    {
     html += '<tr>';
     for(var count = 0; count < data.column.length; count++)
     {
      html += '<th>'+data.column[count]+'</th>';
     }
     html += '</tr>';
    }

    if(data.row_data)
    {
     for(var count = 0; count < data.row_data.length; count++)
     {
      html += '<tr>';
      html += '<td class="student_name" contenteditable>'+data.row_data[count].student_name+'</td>';
      html += '<td class="student_phone" contenteditable>'+data.row_data[count].student_phone+'</td></tr>';
     }
    }
    html += '<table>';
    html += '<div align="center"><button type="button" id="import_data" class="btn btn-success">Import</button></div>';

    $('#csv_file_data').html(html);
    $('#upload_csv')[0].reset();
   }
  })
 });

 $(document).on('click', '#import_data', function(){
  var student_name = [];
  var student_phone = [];
  $('.student_name').each(function(){
   student_name.push($(this).text());
  });
  $('.student_phone').each(function(){
   student_phone.push($(this).text());
  });
  $.ajax({
   url:"import.php",
   method:"post",
   data:{student_name:student_name, student_phone:student_phone},
   success:function(data)
   {
    $('#csv_file_data').html('<div class="alert alert-success">Data Imported Successfully</div>');
   }
  })
 });
});

</script>


fetch.php


This PHP script has received Ajax request for fetch selected CSV file data from Ajax. Here first it has open CSV file by using fopen() function, then after it has read first line which will be table column of CSV file by using fgetcsv() method and store under local variable. After this for read all CSV file data it has use while loop with fgetcsv() method and it has read CSV file data and store data under local variable in array format. And lastly for send response to Ajax request in json format, it has use json_encode() method.


<?php

//fetch.php

if(!empty($_FILES['csv_file']['name']))
{
 $file_data = fopen($_FILES['csv_file']['tmp_name'], 'r');
 $column = fgetcsv($file_data);
 while($row = fgetcsv($file_data))
 {
  $row_data[] = array(
   'student_name'  => $row[0],
   'student_phone'  => $row[1]
  );
 }
 $output = array(
  'column'  => $column,
  'row_data'  => $row_data
 );

 echo json_encode($output);

}

?>


import.php


This script has received Ajax request for insert data into mysql table. First it has verify that there is any ajax has been received for not by using isset() function. If it has received data then it will make database connection and then after it has store array of data store under local variable. For generate multiple insert data query it has loop and after generating multiple insert query it has execute all query at the same time. So, this way it will insert or import multiple data at the same time.


<?php

//import.php

if(isset($_POST["student_name"]))
{
 $connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
 $student_name = $_POST["student_name"];
 $student_phone = $_POST["student_phone"];
 for($count = 0; $count < count($student_name); $count++)
 {
  $query .= "
  INSERT INTO tbl_student(student_name, student_phone) 
  VALUES ('".$student_name[$count]."', '".$student_phone[$count]."');
  
  ";
 }
 $statement = $connect->prepare($query);
 $statement->execute();
}

?>


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_student`
--

CREATE TABLE `tbl_student` (
  `student_id` int(11) NOT NULL,
  `student_name` varchar(250) NOT NULL,
  `student_phone` varchar(20) NOT NULL,
  `image` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Indexes for table `tbl_student`
--
ALTER TABLE `tbl_student`
  ADD PRIMARY KEY (`student_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_student`
--
ALTER TABLE `tbl_student`
  MODIFY `student_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;



Monday, 15 April 2019

Dynamically Add / Remove input fields in Laravel 5.8 using jQuery Ajax



Hi, If you want to use Laravel 5.8 framework for your web development then here we have come with one more advance level of web development topic like How to Add or remove HTML input fields dynamically using jQuery and how to save multiple records in Laravel 5.8 by using Ajax. So, here we have share one more topic on Laravel 5.8 and in this part you can learn how to add more fields using jQuery in Laravel 5.8 application, and for validate dynamically generated input fields we have also implement validation on dynamic generated fields also by using Laravel 5.8 Validator class. So, if you have use Laravel 5.8 for website development purpose and if you add feature like insert or save multiple records at the same time in Laravel 5.8 with Ajax, then this post will help you because in this post we hvae step by step covered How to add or remove textbox dynamically with jQuery and then after by using Ajax with Laravel 5.8 we have save multiple records in Mysql database.

If you are web developer and then in web development we need to sometimes required to insert or save multiple records in Mysql database at the same time. For generate multiple records we want to make multiple fields, for generate dynamic multiple fields here we have use jquery as front-end with Laravel 5.8 application. One of our previous post, we have already covered Add or remove dynamic input fields by using jQuery with PHP. But here we need to do Add or remove dynamically generated fields in jQuery in Laravel 5.8 application. Because this is very useful feature in web application by doing multiple operation in single click or insert or save multiple data into mysql database in single click on Laravel 5.8 application. Here you can also learn how to validate multiple input fields data with same data in Laravel 5.8 validator class. And here also you can learn how to insert or save or add multiple data in Laravel 5.8 application.






Step 1 - Download Laravel 5.8


First we need to download Laravel 5.8 application. For this we have to go to command prompt and write following command. It will download Laravel 5.8 application in your define folder.


composer create-project laravel/laravel=5.8 ajax-crud --prefer-dist


Step 2 - Make Database connection


After install of Laravel 5.8 application, first we wanted to make Mysql database connection. For this you have to open .env file and in that file you have to define Mysql database configuration.


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


Step 3 - Create Table from Laravel 5.8


After making of Mysql database, now we want to create table in Mysql database from Laravel 5.8 application. For this we need to go to command prompt and write following command.


php artisan make:migration create_dynamic_field --create=dynamic_fields

This command will make migration file under database/migarations folder. In that file you have to define table column defination details, which you can find below.


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateDynamicField extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('dynamic_fields', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->timestamps();
        });
    }

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


Now we want to migrate above table defination from Laravel 5.8 application to Mysql database. For this we have to go to command prompt and write following command. This command will make dynamic_fields table under Mysql database.


php artisan migrate


Step 4 - Create Model


For create model under Laravel 5.8 application, we have to go to command prompt and write following command. This command will make DynamicField.php modal file under app folder.


php artisan make:model DynamicField -m


In app/DynamicField.php file we have to define table column name on which we need for database operation.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class DynamicField extends Model
{
    protected $fillable = [
        'first_name', 'last_name'
    ];
}





Step 5 - Create Controller


Controller is the heart of Laravel 5.8 application because it has handle all http request. First we want to make controller, so we have to go to command prompt and write following command. It will make DynamicFieldController.php file under app/Http/Controllers folder.


php artisan make:controller DynamicFieldController


In this controller file you can see below in which we have add two statement in the header. First is use App\DynamicField is for use DynamicField.php modal file use here and second Validator is for use Laravel 5.8 validator class for validate form data. In this controller we have make two method which you can see below.

index() - This is root method of this controller and it will load dynamic_field.blade.php file on web browser as an output.

insert() - This method has received ajax request for insert multiple data. Under this method first it has validate multiple form data of same name. So, here question aris how to validate multiple form data of same name in Laravel 5.8, so here we have add * sign with input field name, which has been used when we have validate multiple form data of the same name in Laravel 5.8 application. If suppose there is any form validation error has been occur then it will send validation error to ajax request in JSON format by using response() method. But suppose there is no any validation error occur then it will continue execute. After this there one more question aris how to insert multiple data in Laravel 5.8 application. So here we have store multiple data in local variable in array format and by using insert() method of modal class, it will insert or save multiple data in Laravel 5.8 application.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\DynamicField;
use Validator;

class DynamicFieldController extends Controller
{
    function index()
    {
     return view('dynamic_field');
    }

    function insert(Request $request)
    {
     if($request->ajax())
     {
      $rules = array(
       'first_name.*'  => 'required',
       'last_name.*'  => 'required'
      );
      $error = Validator::make($request->all(), $rules);
      if($error->fails())
      {
       return response()->json([
        'error'  => $error->errors()->all()
       ]);
      }

      $first_name = $request->first_name;
      $last_name = $request->last_name;
      for($count = 0; $count < count($first_name); $count++)
      {
       $data = array(
        'first_name' => $first_name[$count],
        'last_name'  => $last_name[$count]
       );
       $insert_data[] = $data; 
      }

      DynamicField::insert($insert_data);
      return response()->json([
       'success'  => 'Data Added successfully.'
      ]);
     }
    }
}


Step 6 - Create View file


In this post we have create dynamic_field.blade.php file under resources/views folder. Under this file for generate dynamic input field we have use jQuery code. By using jQuery here it will dynamically generate html input fields. For submit form data here we have use Ajax request, by using ajax request it will send form data to controller method.


<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - DataTables Server Side Processing using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Dynamically Add / Remove input fields in Laravel 5.8 using Ajax jQuery</h3>
     <br />
   <div class="table-responsive">
                <form method="post" id="dynamic_form">
                 <span id="result"></span>
                 <table class="table table-bordered table-striped" id="user_table">
               <thead>
                <tr>
                    <th width="35%">First Name</th>
                    <th width="35%">Last Name</th>
                    <th width="30%">Action</th>
                </tr>
               </thead>
               <tbody>

               </tbody>
               <tfoot>
                <tr>
                                <td colspan="2" align="right">&nbsp;</td>
                                <td>
                  @csrf
                  <input type="submit" name="save" id="save" class="btn btn-primary" value="Save" />
                 </td>
                </tr>
               </tfoot>
           </table>
                </form>
   </div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){

 var count = 1;

 dynamic_field(count);

 function dynamic_field(number)
 {
  html = '<tr>';
        html += '<td><input type="text" name="first_name[]" class="form-control" /></td>';
        html += '<td><input type="text" name="last_name[]" class="form-control" /></td>';
        if(number > 1)
        {
            html += '<td><button type="button" name="remove" id="" class="btn btn-danger remove">Remove</button></td></tr>';
            $('tbody').append(html);
        }
        else
        {   
            html += '<td><button type="button" name="add" id="add" class="btn btn-success">Add</button></td></tr>';
            $('tbody').html(html);
        }
 }

 $(document).on('click', '#add', function(){
  count++;
  dynamic_field(count);
 });

 $(document).on('click', '.remove', function(){
  count--;
  $(this).closest("tr").remove();
 });

 $('#dynamic_form').on('submit', function(event){
        event.preventDefault();
        $.ajax({
            url:'{{ route("dynamic-field.insert") }}',
            method:'post',
            data:$(this).serialize(),
            dataType:'json',
            beforeSend:function(){
                $('#save').attr('disabled','disabled');
            },
            success:function(data)
            {
                if(data.error)
                {
                    var error_html = '';
                    for(var count = 0; count < data.error.length; count++)
                    {
                        error_html += '<p>'+data.error[count]+'</p>';
                    }
                    $('#result').html('<div class="alert alert-danger">'+error_html+'</div>');
                }
                else
                {
                    dynamic_field(1);
                    $('#result').html('<div class="alert alert-success">'+data.success+'</div>');
                }
                $('#save').attr('disabled', false);
            }
        })
 });

});
</script>


Step 7 - Set Route


In Laravel 5.8, we need to set route of all controller method which we have make. For this we have to open routes/web.php file and define following code for set route.


Route::get('dynamic-field', 'DynamicFieldController@index');

Route::post('dynamic-field/insert', 'DynamicFieldController@insert')->name('dynamic-field.insert');


Step 8 - Run Laravel 5.8 application


For run Laravel 5.8 application, we have to go to command prompt and write following command. This command will start Laravel 5.8 application and give you base url of your Laravel 5.8 application.


php artisan serve


For check output in browser you have to write following url in your browser tab.


http://127.0.0.1:8000/dynamic-field




Thursday, 4 April 2019

Laravel 5.8 Ajax Crud Tutorial using DataTables

Part 1




Part 2




Part 3




Part 4




After Learning Simple CRUD (Create, Read, Update, Delete) operation in Laravel 5.8 with file upload, Now we have start learning advance level Crud Application in Laravel 5.8 by using Ajax with jQuery DataTables and Bootstrap Modal. So, user can perform all Crud operation on same without refresh of web page. Because here it will make single page Ajax Crud Application with File Upload in Laravel 5.8 by jQuery DataTables server side processing and form operation done by using Bootstrap modal.

For make Laravel 5.8 Crud Application using Ajax with DataTables and Bootstrap model. So first for use DataTables with Laravel 5.8, here we have will use Yajra DataTables package. By using Yajra Laravel DataTables plugin we can easily implement Server Side Processing of Data in Laravel 5.8 framework. So, User can list all records in tabular formate with different features like pagination of data, sorting of data and filter or search of data.

Same way for perform all Insert Update Delete data using Ajax in Laravel 5.8 framework. Here we will use Bootstrap modal. By using Bootstrap modal, we will make form in modal, because modal will pop up Insert data or edit data form on web page. So, user can perform all add edit delete data operation on single page in Laravel 5.8 using Ajax. Below you can step by step process of implementing Ajax Crud tutorial in Laravel 5.8 using Yajra DataTables package and Bootstrap modal.


Laravel 5.8 Ajax Crud Tutorial using DataTables



Step 1 - Install Laravel 5.8


First we want to Download Laravel 5.8 version for developing Crud application using Ajax. For this you have to open your terminal or command prompt and write below command. It will download Laravel 5.8 in your define directory.


composer create-project laravel/laravel=5.8 ajax-crud --prefer-dist


Step 2 - Laravel 5.8 Database Connection


Once Laravel 5.8 has been downloaded then after we have to make Database connection. For this first you have to open config/database.php and define Mysql Database configuration.



.......

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'testing'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]),
        ],

........


After this you have to open .env file and in that file also you have to define Mysql Database configuration, which you can find below.



.......

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

........


Step 3 - Create Table


For Create Crud Application, first we have to create Mysql table. For create Mysql table from Laravel 5.8 application we have to write following artisan command in your command prompt.


php artisan make:migration create_ajax_cruds_table --create=ajax_cruds


Above command will command create migration file in database/migrations folder. In that file we have to define table column which you want to define in Mysql table. Below you can find source code of migration file.


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAjaxCrudsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('ajax_cruds', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('image');
            $table->timestamps();
        });
    }

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


Lastly for create Mysql table in your Database, you have to write following command in your terminal or command prompt. It will create ajax_cruds table in your define Database.


php artisan migrate


Step 4 - Create Model in Laravel 5.8


Now we want to make Model in Laravel 5.8, For this you have to write following command in your terminal or command prompt. It will create model file here app/AjaxCrud.php.


php artisan make:model AjaxCrud -m


Under this app/AjaxCrud.php file, you have to define table column for database operation which source code you can find below.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class AjaxCrud extends Model
{
    protected $fillable = [
     'first_name', 'last_name', 'image'
    ];
}


Step 5 - Install Yajra DataTabbles Package in Laravel 5.8


For use jQuery DataTables plugin in Laravel 5.8, for this first we want to install Yajra DataTables plugin in Laravel 5.8 application. For this we have to write following command in your computer terminal or command prompt.


composer require yajra/laravel-datatables-oracle


Above command will download Yajra DataTables package in your Laravel 5.8 application. For use of Yajra DataTables package in Laravel 5.8 framework, we have to set this package providers and alias details.


.....
'providers' => [
 ....
 Yajra\Datatables\DatatablesServiceProvider::class,
]
'aliases' => [
 ....
 'Datatables' => Yajra\Datatables\Facades\Datatables::class,
]
.....


Lastly we want to publish this Yajra DataTables package, for this we have to write following command.


php artisan vendor:publish





Step 6 - Create Controller in Laravel 5.8


Controller mostly used for handle HTTP request. Create new controller in Laravel 5.8 framework, we have to write following command.


php artisan make:controller AjaxCrudController --resource


This command will create AjaxCrudController.php file in app/Http/Controllers folder. In this controller file you can find all in build required method for do Crud operation. Under this controller for use AjaxCrud model, first we have to define use App\AjaxCrud; this statement at the header of the AjaxCrudController.php file.

index() - This is the root method of this controller. This method will received Ajax request for load data in jQuery DataTables plugin. If this method received ajax request then it will load data in jQuery DataTables plugin. In this ajax block you can find yajra datatables package code.

store() - For Insert Data into Mysql table using ajax in Laravel 5.8, here we have use store() method of AjaxCrudController.php. This method will received Ajax request for insert or add data. Under this method first it has validate for data. If there is any validation fails then it will send response to ajax request in JSON format. But there is no any validation fails then it will continue execution of code and first it will upload profile image of user and then after it will insert data into mysql table. And lastly it will send json response to ajax request.

edit() - This method is used for fetch single row of data from mysql table, and send data to ajax request in json formate which will be display under Bootstrap modal form.

update() - This method has received ajax request for update existing mysql table data. In this method first it check user has select profile image or not. If User is select image then in this method it will validate form data with selected file is image or not. But Suppose user has not select image then it will only validate textbox data only. If there is any validation error occur then it will send data to ajax request in json formate. After successfully validate form data then it will update data.

destroy() - For delete or remove mysql data, ajax request will be send to destroy() method. It will delete or remove mysql data in Laravel 5.8 by using ajax.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\AjaxCrud;
use Validator;

class AjaxCrudController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if(request()->ajax())
        {
            return datatables()->of(AjaxCrud::latest()->get())
                    ->addColumn('action', function($data){
                        $button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Edit</button>';
                        $button .= '&nbsp;&nbsp;';
                        $button .= '<button type="button" name="delete" id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
                        return $button;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
        return view('ajax_index');
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $rules = array(
            'first_name'    =>  'required',
            'last_name'     =>  'required',
            'image'         =>  'required|image|max:2048'
        );

        $error = Validator::make($request->all(), $rules);

        if($error->fails())
        {
            return response()->json(['errors' => $error->errors()->all()]);
        }

        $image = $request->file('image');

        $new_name = rand() . '.' . $image->getClientOriginalExtension();

        $image->move(public_path('images'), $new_name);

        $form_data = array(
            'first_name'        =>  $request->first_name,
            'last_name'         =>  $request->last_name,
            'image'             =>  $new_name
        );

        AjaxCrud::create($form_data);

        return response()->json(['success' => 'Data Added successfully.']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        if(request()->ajax())
        {
            $data = AjaxCrud::findOrFail($id);
            return response()->json(['data' => $data]);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $image_name = $request->hidden_image;
        $image = $request->file('image');
        if($image != '')
        {
            $rules = array(
                'first_name'    =>  'required',
                'last_name'     =>  'required',
                'image'         =>  'image|max:2048'
            );
            $error = Validator::make($request->all(), $rules);
            if($error->fails())
            {
                return response()->json(['errors' => $error->errors()->all()]);
            }

            $image_name = rand() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('images'), $image_name);
        }
        else
        {
            $rules = array(
                'first_name'    =>  'required',
                'last_name'     =>  'required'
            );

            $error = Validator::make($request->all(), $rules);

            if($error->fails())
            {
                return response()->json(['errors' => $error->errors()->all()]);
            }
        }

        $form_data = array(
            'first_name'       =>   $request->first_name,
            'last_name'        =>   $request->last_name,
            'image'            =>   $image_name
        );
        AjaxCrud::whereId($request->hidden_id)->update($form_data);

        return response()->json(['success' => 'Data is successfully updated']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $data = AjaxCrud::findOrFail($id);
        $data->delete();
    }
}


Step 7 - Create Blades Files


For display output data in browser, in Laravel 5.8 we have to create blade file in resources/views folder. Under this folder we have create ajax_index.blade.php file. In this file you can find HTML code and jQuery code for display data in jQuery Datatable.


<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - DataTables Server Side Processing using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 Ajax Crud Tutorial - Delete or Remove Data</h3>
     <br />
     <div align="right">
      <button type="button" name="create_record" id="create_record" class="btn btn-success btn-sm">Create Record</button>
     </div>
     <br />
   <div class="table-responsive">
    <table class="table table-bordered table-striped" id="user_table">
           <thead>
            <tr>
                <th width="10%">Image</th>
                <th width="35%">First Name</th>
                <th width="35%">Last Name</th>
                <th width="30%">Action</th>
            </tr>
           </thead>
       </table>
   </div>
   <br />
   <br />
  </div>
 </body>
</html>

<div id="formModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Add New Record</h4>
        </div>
        <div class="modal-body">
         <span id="form_result"></span>
         <form method="post" id="sample_form" class="form-horizontal" enctype="multipart/form-data">
          @csrf
          <div class="form-group">
            <label class="control-label col-md-4" >First Name : </label>
            <div class="col-md-8">
             <input type="text" name="first_name" id="first_name" class="form-control" />
            </div>
           </div>
           <div class="form-group">
            <label class="control-label col-md-4">Last Name : </label>
            <div class="col-md-8">
             <input type="text" name="last_name" id="last_name" class="form-control" />
            </div>
           </div>
           <div class="form-group">
            <label class="control-label col-md-4">Select Profile Image : </label>
            <div class="col-md-8">
             <input type="file" name="image" id="image" />
             <span id="store_image"></span>
            </div>
           </div>
           <br />
           <div class="form-group" align="center">
            <input type="hidden" name="action" id="action" />
            <input type="hidden" name="hidden_id" id="hidden_id" />
            <input type="submit" name="action_button" id="action_button" class="btn btn-warning" value="Add" />
           </div>
         </form>
        </div>
     </div>
    </div>
</div>

<div id="confirmModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h2 class="modal-title">Confirmation</h2>
            </div>
            <div class="modal-body">
                <h4 align="center" style="margin:0;">Are you sure you want to remove this data?</h4>
            </div>
            <div class="modal-footer">
             <button type="button" name="ok_button" id="ok_button" class="btn btn-danger">OK</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>


<script>
$(document).ready(function(){

 $('#user_table').DataTable({
  processing: true,
  serverSide: true,
  ajax:{
   url: "{{ route('ajax-crud.index') }}",
  },
  columns:[
   {
    data: 'image',
    name: 'image',
    render: function(data, type, full, meta){
     return "<img src={{ URL::to('/') }}/images/" + data + " width='70' class='img-thumbnail' />";
    },
    orderable: false
   },
   {
    data: 'first_name',
    name: 'first_name'
   },
   {
    data: 'last_name',
    name: 'last_name'
   },
   {
    data: 'action',
    name: 'action',
    orderable: false
   }
  ]
 });

 $('#create_record').click(function(){
  $('.modal-title').text("Add New Record");
     $('#action_button').val("Add");
     $('#action').val("Add");
     $('#formModal').modal('show');
 });

 $('#sample_form').on('submit', function(event){
  event.preventDefault();
  if($('#action').val() == 'Add')
  {
   $.ajax({
    url:"{{ route('ajax-crud.store') }}",
    method:"POST",
    data: new FormData(this),
    contentType: false,
    cache:false,
    processData: false,
    dataType:"json",
    success:function(data)
    {
     var html = '';
     if(data.errors)
     {
      html = '<div class="alert alert-danger">';
      for(var count = 0; count < data.errors.length; count++)
      {
       html += '<p>' + data.errors[count] + '</p>';
      }
      html += '</div>';
     }
     if(data.success)
     {
      html = '<div class="alert alert-success">' + data.success + '</div>';
      $('#sample_form')[0].reset();
      $('#user_table').DataTable().ajax.reload();
     }
     $('#form_result').html(html);
    }
   })
  }

  if($('#action').val() == "Edit")
  {
   $.ajax({
    url:"{{ route('ajax-crud.update') }}",
    method:"POST",
    data:new FormData(this),
    contentType: false,
    cache: false,
    processData: false,
    dataType:"json",
    success:function(data)
    {
     var html = '';
     if(data.errors)
     {
      html = '<div class="alert alert-danger">';
      for(var count = 0; count < data.errors.length; count++)
      {
       html += '<p>' + data.errors[count] + '</p>';
      }
      html += '</div>';
     }
     if(data.success)
     {
      html = '<div class="alert alert-success">' + data.success + '</div>';
      $('#sample_form')[0].reset();
      $('#store_image').html('');
      $('#user_table').DataTable().ajax.reload();
     }
     $('#form_result').html(html);
    }
   });
  }
 });

 $(document).on('click', '.edit', function(){
  var id = $(this).attr('id');
  $('#form_result').html('');
  $.ajax({
   url:"/ajax-crud/"+id+"/edit",
   dataType:"json",
   success:function(html){
    $('#first_name').val(html.data.first_name);
    $('#last_name').val(html.data.last_name);
    $('#store_image').html("<img src={{ URL::to('/') }}/images/" + html.data.image + " width='70' class='img-thumbnail' />");
    $('#store_image').append("<input type='hidden' name='hidden_image' value='"+html.data.image+"' />");
    $('#hidden_id').val(html.data.id);
    $('.modal-title').text("Edit New Record");
    $('#action_button').val("Edit");
    $('#action').val("Edit");
    $('#formModal').modal('show');
   }
  })
 });

 var user_id;

 $(document).on('click', '.delete', function(){
  user_id = $(this).attr('id');
  $('#confirmModal').modal('show');
 });

 $('#ok_button').click(function(){
  $.ajax({
   url:"ajax-crud/destroy/"+user_id,
   beforeSend:function(){
    $('#ok_button').text('Deleting...');
   },
   success:function(data)
   {
    setTimeout(function(){
     $('#confirmModal').modal('hide');
     $('#user_table').DataTable().ajax.reload();
    }, 2000);
   }
  })
 });

});
</script>


Step 8 - Set Resource Route


Lastly, We need to set resource route for ajax crud application. For this we have to open routes/web.php file.


Route::resource('ajax-crud', 'AjaxCrudController');

Route::post('ajax-crud/update', 'AjaxCrudController@update')->name('ajax-crud.update');

Route::get('ajax-crud/destroy/{id}', 'AjaxCrudController@destroy');


For run Laravel 5.8 application, you can write following command.


php artisan serve


For see Laravel 5.8 application in your browser, you have to write following url.


http://localhost:8000/ajax-crud