Wednesday, 27 February 2019

How to use jqBootstrapValidation for Validate Form with Ajax PHP



This one more Webslesson post on How to validate form data using jQuery plugin. Now in this post we have use jqBoostrapValidation plugin for validate form data and make spam free contact form with Ajax and PHP. In one of previous post, we have use parsleyjs for form data validation and submit form data using Ajax. Here also we will show you how to validate form data by using jqBootstraoValidation plugin and submit form data using Ajax with PHP.

jqBootstrapValidation is a jQuery plugin for validate bootstrap form data. It mainly display validation error in help-block of Bootstrap library class. It is a simple form validation plugin, which mainly used with Bootstrap library. If you have use Bootstrap library for your front end use, then it will help you in form validation. Because it has used Bootstrap library element as users type. Validation of Form data is a headache of every programmer, but if you have used bootstrap library, then this plugin will helpful to validate form data.

This plugin has used HTML5 validator attributes on html field, and it has used data attributes for display error. If you want to set any input, which data has required for submit form, then at that time you can simply used requred="required" attribute, then this plugin will directly scan this HTML5 attributes for validate that input field. Now question aris how can we display error of that validation, then in this plugin used data-validation-required-message attributes has been used for display required validation error.

After this suppose you want to validate email fields data, for this you have to just used input="email" this plugin will automatically generates error if email fields data in not in proper email format.

Same way, we want to validate mobile number in form field, then at that time we can use pattern attributes like pattern="^[0-9]{10}$" this pattern will validate mobile number which must be in number format with the length 10 digit if data is not in this format then it will display error. For display pattern validation error, this plugin has use data-validation-pattern-message this data attribute for display pattern mismatch validation error. If you want to get details documentation of this plugin, you can get here.






Source Code


index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Contact Form Validation using jqBootstrapValidation with Ajax PHP</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>  
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jqBootstrapValidation/1.3.6/jqBootstrapValidation.js"></script>
  <style>
  .box
  {
   max-width:600px;
   width:100%;
   margin: 0 auto;;
  }
        .form-group p
        {
            color:#a94442;
        }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Contact Form Validation using jqBootstrapValidation with Ajax PHP</h3>
   <br />
   <form id="simple_form" novalidate="novalidate">

    <div class="control-group">
                    <div class="form-group mb-0 pb-2">
                        <input type="text" name="contact_name" id="contact_name" class="form-control form-control-lg" placeholder="Name" required="required" data-validation-required-message="Please enter your name." />
                        <p class="text-danger help-block"></p>
                    </div>
                </div>

                <div class="control-group">
                    <div class="form-group">
                        <input type="email" name="contact_email" id="contact_email" class="form-control form-control-lg" placeholder="Email Address" required="required" data-validation-required-message="Please enter your email address." />
                        <p class="text-danger help-block"></p>

                    </div>
                </div>

                <div class="control-group">
                    <div class="form-group">
                        <input type="tel" name="contact_mobile" id="contact_mobile" class="form-control form-control-lg" placeholder="Phone Number" required="required" data-validation-required-message="Please enter your phone number." pattern="^[0-9]{10}$" data-validation-pattern-message="10 digits needed" />
                        <p class="text-danger help-block"></p>

                    </div>
                </div>

                <div class="control-group">
                    <div class="form-group">
                        <textarea name="contact_message" id="contact_message" class="form-control form-control-lg" rows="5" placeholder="Message" required="required" data-validation-required-message="Please enter a message."></textarea>
                        <p class="text-danger help-block"></p>
                    </div>
                </div>
                <br>
                <div id="success"></div>
                <div class="form-group">
                 <button type="submit" class="btn btn-primary" id="send_button">Send</button>
                </div>
   </form>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
    $('#simple_form input, #simple_form textarea').jqBootstrapValidation({
     preventSubmit: true,
     submitSuccess: function($form, event){     
      event.preventDefault();
      $this = $('#send_button');
      $this.prop('disabled', true);
      var form_data = $("#simple_form").serialize();
      $.ajax({
       url:"send.php",
       method:"POST",
       data:form_data,
       success:function(){
        $('#success').html("<div class='alert alert-success'><strong>Your message has been sent. </strong></div>");
        $('#simple_form').trigger('reset');
       },
       error:function(){
        $('#success').html("<div class='alert alert-danger'>There is some error</div>");
        $('#simple_form').trigger('reset');
       },
       complete:function(){
        setTimeout(function(){
         $this.prop("disabled", false);
         $('#success').html('');
        }, 5000);
       }
      });
     },
    });

});
</script>





send.php



<?php

//send.php

if(isset($_POST["contact_name"]))
{
 require 'class/class.phpmailer.php';
 $mail = new PHPMailer;
 $mail->IsSMTP();
 $mail->Host = 'smtpout.secureserver.net';

 $mail->Port = '80';

 $mail->SMTPAuth = true;
 $mail->Username = 'xxxx';
 $mail->Password = 'xxxx'; 
 $mail->SMTPSecure = '';
 $mail->From = $_POST['contact_email'];
 $mail->FromName = $_POST['contact_name'];
 $mail->AddAddress('web-tutorial@programmer.net');
 $mail->WordWrap = 50;
 $mail->IsHTML(true);

 $mail->Subject = 'New Business Enquiry from ' . $_POST['contact_name'];
 $message_body = $_POST["contact_message"];
 $message_body .= '<p>With mobile number ' . $_POST["contact_mobile"] . '</p>';
 $mail->Body = $message_body;

 if($mail->Send())
 {
  echo 'Thank you for Contact Us';
 }
}

?>

This is complete step by process of how use jqBootstrapValidation library for validate form data with Ajax request and PHP script.





Monday, 25 February 2019

Import Excel File in Laravel



If you are using Laravel Framework for your web development, and if you are beginner in Laravel. Then this post will help you to learn something new in Laravel. Because in this post you can find how to import Excel spreadsheet data and insert into mysql database in Laravel. Here for importing Excel file data here we will use Laravel Maatwebsite package. By using this package we can easily import data from Excel sheet and insert into table in Laravel application.

In some of the businees houses in which there are many large number of data has been stored in Excel, and after storing that data, they want some application which helps them to store in web application database, that means import into web application database. Then at that time if your web application has been made in PHP Laravel framewor then this post will help you to make importing excel file data feature in Laravel application by using Maatwebsite package.

In this post we will see or learn how can we import any type of Excel speadsheet in .xls, .xlsx or CSV data imported into Mysql database in Laravel. For communicate excel file data in Laravel, here have use Maatwebsite Laravel Excel package, this package will help to communicate excel file data in Laravel application. Below you can find complete step by step process of how to use Laravel maatwebsite package for import Excel sheet data into database in Laravel.






Step 1 - Create Table


First, we have to create table in Mysql Database, so run following SQL script, it will make tbl_customer table in your database.


--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_customer`
--

CREATE TABLE `tbl_customer` (
  `CustomerID` int(11) NOT NULL,
  `CustomerName` varchar(250) NOT NULL,
  `Gender` varchar(30) NOT NULL,
  `Address` text NOT NULL,
  `City` varchar(250) NOT NULL,
  `PostalCode` varchar(30) NOT NULL,
  `Country` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Indexes for table `tbl_customer`
--
ALTER TABLE `tbl_customer`
  ADD PRIMARY KEY (`CustomerID`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_customer`
--
ALTER TABLE `tbl_customer`
  MODIFY `CustomerID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=146;


Step 2 - Mysql Database connection in Laravel


After this you have to make database connection. For this first you have to open database.php file from config. And in this file you have to define your database configuration.


<?php

return [


    'default' => env('DB_CONNECTION', 'mysql'),

...........

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            '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' => '',
            'strict' => true,
            'engine' => null,
        ],

.............

];



After this you have to open .env file, and in this file also you have to define Mysql database configuration also.


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


Step 3 - Download Maatwebsite Package


If you want to import excel file data in Laravel, you have to first download Maatwebsite package, this package will communicate with Excel spreadsheet data. First for download package, you have to go to command prompt and write following command.


composer require maatwebsite/excel


This command will download this package in your Laravel working folder. After this we have to register this package in our Laravel application. For this we have to go to config/app.php file. And in this file you have to define providers and aliases.


<?php

return [

........

    'providers' => [

.......

        Maatwebsite\Excel\ExcelServiceProvider::class,

    ],

    'aliases' => [

........
        
        'Excel' => Maatwebsite\Excel\Facades\Excel::class,

    ],

];



This way we can register Maatwebsite package in Laravel application, now we can use this package for importing excel file data.

Step 4 - Controllers (ImportExcelController.php)


Now we have to make controller for handle http request for import data. In this controller we have use two use statement. First use DB is used for do mysql database operation, and second use Excel is for Maatwebsite package for import excel sheet data. In this controller, we have make two method.

index() - This is root method of this class, in this method it will fetch data from customer table and that data will be load in import_blade.php file in table format.

import() - This method has request for import excel file data. In this method first it has validate excel file format. If selected file other than excel sheet then it will return validation error. But suppose selected file is excel then it will proceed for import data. For import data here it has called Excel package class which has get data from excel file and convert into PHP array and then after insert into customer table. After successfully import of data it will return success message.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use Excel;

class ImportExcelController extends Controller
{
    function index()
    {
     $data = DB::table('tbl_customer')->orderBy('CustomerID', 'DESC')->get();
     return view('import_excel', compact('data'));
    }

    function import(Request $request)
    {
     $this->validate($request, [
      'select_file'  => 'required|mimes:xls,xlsx'
     ]);

     $path = $request->file('select_file')->getRealPath();

     $data = Excel::load($path)->get();

     if($data->count() > 0)
     {
      foreach($data->toArray() as $key => $value)
      {
       foreach($value as $row)
       {
        $insert_data[] = array(
         'CustomerName'  => $row['customer_name'],
         'Gender'   => $row['gender'],
         'Address'   => $row['address'],
         'City'    => $row['city'],
         'PostalCode'  => $row['postal_code'],
         'Country'   => $row['country']
        );
       }
      }

      if(!empty($insert_data))
      {
       DB::table('tbl_customer')->insert($insert_data);
      }
     }
     return back()->with('success', 'Excel Data Imported successfully.');
    }
}






Step 5 - View File (import_excel.blade.php)


This file has been load by index() method of ImportExcelController, On this file we have make form for select excel file from local computer for import data. Below form it will display tbl_customer table data. And above form we have define for display validation error message and success message.


<!DOCTYPE html>
<html>
 <head>
  <title>Import Excel File in Laravel</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  
  <div class="container">
   <h3 align="center">Import Excel File in Laravel</h3>
    <br />
   @if(count($errors) > 0)
    <div class="alert alert-danger">
     Upload Validation Error<br><br>
     <ul>
      @foreach($errors->all() as $error)
      <li>{{ $error }}</li>
      @endforeach
     </ul>
    </div>
   @endif

   @if($message = Session::get('success'))
   <div class="alert alert-success alert-block">
    <button type="button" class="close" data-dismiss="alert">×</button>
           <strong>{{ $message }}</strong>
   </div>
   @endif
   <form method="post" enctype="multipart/form-data" action="{{ url('/import_excel/import') }}">
    {{ csrf_field() }}
    <div class="form-group">
     <table class="table">
      <tr>
       <td width="40%" align="right"><label>Select File for Upload</label></td>
       <td width="30">
        <input type="file" name="select_file" />
       </td>
       <td width="30%" align="left">
        <input type="submit" name="upload" class="btn btn-primary" value="Upload">
       </td>
      </tr>
      <tr>
       <td width="40%" align="right"></td>
       <td width="30"><span class="text-muted">.xls, .xslx</span></td>
       <td width="30%" align="left"></td>
      </tr>
     </table>
    </div>
   </form>
   
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Customer Data</h3>
    </div>
    <div class="panel-body">
     <div class="table-responsive">
      <table class="table table-bordered table-striped">
       <tr>
        <th>Customer Name</th>
        <th>Gender</th>
        <th>Address</th>
        <th>City</th>
        <th>Postal Code</th>
        <th>Country</th>
       </tr>
       @foreach($data as $row)
       <tr>
        <td>{{ $row->CustomerName }}</td>
        <td>{{ $row->Gender }}</td>
        <td>{{ $row->Address }}</td>
        <td>{{ $row->City }}</td>
        <td>{{ $row->PostalCode }}</td>
        <td>{{ $row->Country }}</td>
       </tr>
       @endforeach
      </table>
     </div>
    </div>
   </div>
  </div>
 </body>
</html>


Step 6 - Set Route


After this we have to set the route of controller method. For this we have to open to routes/web.php file. In this file we can define route.


<?php

.......

Route::get('/import_excel', 'ImportExcelController@index');
Route::post('/import_excel/import', 'ImportExcelController@import');


Step 7 - Run Laravel Application


Lastly, we have to run Laravel application, for this we have to go to command prompt, and write following command.


php artisan serve


This command will Laravel application, it will return base url of Laravel application. Now for this application, we have to write following url in browser.


http://127.0.0.1:8000/import_excel


Above is the complete process of How to make import excel file data feature in Laravel using Maatwebsite Package.

Friday, 22 February 2019

Ajax jQuery Load More Data in Laravel



If you have seen any social media sites like Youtube, Twitter or Facebook, in which when page has been load then it has not load all data on web page, when it was load in browser. But in all those sites they have load only last some data on web page, and suppose we want to view more data, then we have to click on load more button. So, this types of techniques we have to implement in Laravel by using ajax jQuery. In this features data will be load dynamically, when user have been click on button, and here it will make pagination without displaying links to user.

Load More or Show More functionality is very simple and user friendly, this is because here all data has not been load at the same time, but it will load only after click on button like pagination, but also it will load more data without refreshing of web page. In this post we will make this type of feature like Load more data from Mysql Database using Ajax in Laravel Framework.

There are two type of load more data feature, one is when user has been click on button then next records has been load on web page, and other is when page has been scroll then next data has been load on web page. But here we will implement load more data on button click event, which we will make in Laravel framework using Ajax jQuery. It will works in a very simple way, and when page has been load then it will load some specific number of data, Suppose we want to view next records, then we have to click on button in which we have define last data id and based on that id it will append next data on web page without refresh of whole page. Because here we have use Ajax with Laravel for implement Load More feature.




Ajax jQuery Load More Data in Laravel


Step 1 - Create Database


Following script will make table in your database.


USE `testing`;

/*Table structure for table `post` */

DROP TABLE IF EXISTS `post`;

CREATE TABLE `post` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `post_title` text,
  `post_description` text,
  `author` varchar(255) DEFAULT NULL,
  `date` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=latin1;


Step 2 - Make Database Connection


Once you have create table, and you have insert some records in that table. Now we have move to start creating Load More feature in Laravel. First we want to make database connection. For this we have to go to config/database.php. In this file we have to define database configuration.


<?php

'connections' => [

        ....

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            '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' => '',
            'strict' => false,
            'engine' => null,
        ],

        ..........

    ],

?>


After this we have to open .env file, and this file also we have to define Mysql Database connection configuration.


.......

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

........


Step 3 - Create Controller (LoadMoreController.php)


After making Mysql Database connection, Now we have to create Controller in Laravel. For this we have to go to command prompt, in which first we have to run "Composer" command, because it has manage Laravel framework dependency. We have to write following command for Create controller in Laravel.


php artisan make:controller LoadMoreController


It will make LoadMoreController.php file under app/Http/Controllers folder. In this controller we have use DB statement for database operation. In this controller we have make following method.

index() - This is root method of this LoadMoreController, which has been load load_more.blade.php file in browser.

load_data() - This method has received ajax request for fetch data from post table and convert into html format and send back to ajax request. In this method if id variable value greater than zero then it will fetch next five data, otherwise it has fetch first five data and convert into HTML and send to Ajax funciton, which has been display on web page.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class LoadMoreController extends Controller
{
    function index()
    {
     return view('load_more');
    }

    function load_data(Request $request)
    {
     if($request->ajax())
     {
      if($request->id > 0)
      {
       $data = DB::table('post')
          ->where('id', '<', $request->id)
          ->orderBy('id', 'DESC')
          ->limit(5)
          ->get();
      }
      else
      {
       $data = DB::table('post')
          ->orderBy('id', 'DESC')
          ->limit(5)
          ->get();
      }
      $output = '';
      $last_id = '';
      
      if(!$data->isEmpty())
      {
       foreach($data as $row)
       {
        $output .= '
        <div class="row">
         <div class="col-md-12">
          <h3 class="text-info"><b>'.$row->post_title.'</b></h3>
          <p>'.$row->post_description.'</p>
          <br />
          <div class="col-md-6">
           <p><b>Publish Date - '.$row->date.'</b></p>
          </div>
          <div class="col-md-6" align="right">
           <p><b><i>By - '.$row->author.'</i></b></p>
          </div>
          <br />
          <hr />
         </div>         
        </div>
        ';
        $last_id = $row->id;
       }
       $output .= '
       <div id="load_more">
        <button type="button" name="load_more_button" class="btn btn-success form-control" data-id="'.$last_id.'" id="load_more_button">Load More</button>
       </div>
       ';
      }
      else
      {
       $output .= '
       <div id="load_more">
        <button type="button" name="load_more_button" class="btn btn-info form-control">No Data Found</button>
       </div>
       ';
      }
      echo $output;
     }
    }
}

?>






Step 4 - Create View (load_more.blade.php)


In Laravel, it has use blade engine for process PHP file which has been store under resources/views/load_more.blade.php, it is has display output in browser. Under this file we have use ajax request, which send request to Controller for fetch data and display on web page without refresh of web page. For append data on web page, here we have use jquery append() method.


<!DOCTYPE html>
<html>
 <head>
  <title>Load More Data in Laravel using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container box">
   <h3 align="center">Load More Data in Laravel using Ajax</h3><br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Post Data</h3>
    </div>
    <div class="panel-body">
     {{ csrf_field() }}
     <div id="post_data"></div>
    </div>
   </div>
   <br />
   <br />
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 var _token = $('input[name="_token"]').val();

 load_data('', _token);

 function load_data(id="", _token)
 {
  $.ajax({
   url:"{{ route('loadmore.load_data') }}",
   method:"POST",
   data:{id:id, _token:_token},
   success:function(data)
   {
    $('#load_more_button').remove();
    $('#post_data').append(data);
   }
  })
 }

 $(document).on('click', '#load_more_button', function(){
  var id = $(this).data('id');
  $('#load_more_button').html('<b>Loading...</b>');
  load_data(id, _token);
 });

});
</script>


Step 5 - Set Route


After this we have to set route of Controller method in Laravel framework. For this we have to open routes/web.php file.


Route::get('/loadmore', 'LoadMoreController@index');
Route::post('/loadmore/load_data', 'LoadMoreController@load_data')->name('loadmore.load_data');


Step 6 - Run Laravel Application


For run Laravel application, we have to go command prompt and write following commend, it will run Laravel application and display base url of Laravel application.


php artisan serve


It will return follwing url and for run this code you have to write following url.


http //127.0.0.1


This is complete step by step process with source code for make Load More data feature in Laravel by using Ajax jQuery with Mysql Database.

Tuesday, 19 February 2019

Laravel Date Range Search using Ajax jQuery



In this post, We are going to learn how to search database data which has come between two dates. That means it will return filter data from the mysql database based on two dates input. So, this type of feature we will make in Laravel PHP framework by using Ajax jQuery. So, Data comes between two dates will be load on web page without refresh of web page, because here we will use Ajax with Laravel for Date Range Search.

Here we will use Bootstrap Datepicker plugin for choose the dates for filter data options. By using this plugin we will enable Data selection on textbox, so user can select from date and to data inputs, when he will click on button, then ajax request will be send to Laravel script, which will search data which has been come between two provided date by using BETWEEN clause. So, here we will make date range search with Bootstrap Datepicker using Ajax with Laravel framework and Mysql database.

If you have make any enterprise level application using Laravel framework, and in that system you have large amount of data, then you have to filter data. So filtering of data there is one option is Date Range search. Date Range search means how to get records comes between two given date. So, this type of feature here we will make in Laravel application. So, here we will search data with date range in Laravel. Below you can find step by step process for how to implement Date Range Search feature in Laravel using Ajax.




Laravel Date Range Search using Ajax jQuery


Step 1 - Database Table


Run following sql script, it will make post table in your phpmyadmin.


USE `testing`;

/*Table structure for table `post` */

DROP TABLE IF EXISTS `post`;

CREATE TABLE `post` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `post_title` text,
  `post_description` text,
  `author` varchar(255) DEFAULT NULL,
  `date` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=latin1;


Step 2 - Laravel Database connection


Once table has been created in your database, now you have to make database connection, for this first you have to go to config/database.php and in this you have to define your database configuration.


......

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            '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' => '',
            'strict' => false,
            'engine' => null,
        ],

.....


After this you have to open .env file, and in this file also you have to define Database configuration. So, in Larave this two place we have to define Database configuration for make database connection.


.....


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

.......


Step 3 - Create Controller in Laravel (DateRangeController.php)


For create controller in Laravel. first you have to go to your command prompt, and in that you have to first run composer command. This is because laravel all dependecy has been manage by using composer. After this you have to go to working folder, and write following command.


.....

php artisan make:controller DateRangeController

.......


This command will make DateRangeController.php controller file in app/Http/Controllers folder. In this file we have make two method.

index() - This is root method of this class, it will load date_range.php file in browser.

fetch_data() -
This method has received ajax request for search data comes between two dates. In this method we have perform database operation, and it will return data in json format.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class DateRangeController extends Controller
{
    function index()
    {
     return view('date_range');
    }

    function fetch_data(Request $request)
    {
     if($request->ajax())
     {
      if($request->from_date != '' && $request->to_date != '')
      {
       $data = DB::table('post')
         ->whereBetween('date', array($request->from_date, $request->to_date))
         ->get();
      }
      else
      {
       $data = DB::table('post')->orderBy('date', 'desc')->get();
      }
      echo json_encode($data);
     }
    }
}

?>





Step 4 - View File (data_range.blade.php)


This view you have to make in resources/views folder. This view file has been used for display html output in browser. In this file we have use jQuery, Bootstrap and Datepicker librar for date selection. Here we have used Ajax request for fetch data from server. Below you can find code of this file.


<!DOCTYPE html>
<html>
 <head>
  <title>Date Range Fiter Data in Laravel using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.js"></script>
 </head>
 <body>
  <br />
  <div class="container box">
   <h3 align="center">Date Range Fiter Data in Laravel using Ajax</h3><br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-5">Sample Data - Total Records - <b><span id="total_records"></span></b></div>
      <div class="col-md-5">
       <div class="input-group input-daterange">
           <input type="text" name="from_date" id="from_date" readonly class="form-control" />
           <div class="input-group-addon">to</div>
           <input type="text"  name="to_date" id="to_date" readonly class="form-control" />
       </div>
      </div>
      <div class="col-md-2">
       <button type="button" name="filter" id="filter" class="btn btn-info btn-sm">Filter</button>
       <button type="button" name="refresh" id="refresh" class="btn btn-warning btn-sm">Refresh</button>
      </div>
     </div>
    </div>
    <div class="panel-body">
     <div class="table-responsive">
      <table class="table table-striped table-bordered">
       <thead>
        <tr>
         <th width="35%">Post Title</th>
         <th width="50%">Post Description</th>
         <th width="15%">Publish Date</th>
        </tr>
       </thead>
       <tbody>
       
       </tbody>
      </table>
      {{ csrf_field() }}
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

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

 var date = new Date();

 $('.input-daterange').datepicker({
  todayBtn: 'linked',
  format: 'yyyy-mm-dd',
  autoclose: true
 });

 var _token = $('input[name="_token"]').val();

 fetch_data();

 function fetch_data(from_date = '', to_date = '')
 {
  $.ajax({
   url:"{{ route('daterange.fetch_data') }}",
   method:"POST",
   data:{from_date:from_date, to_date:to_date, _token:_token},
   dataType:"json",
   success:function(data)
   {
    var output = '';
    $('#total_records').text(data.length);
    for(var count = 0; count < data.length; count++)
    {
     output += '<tr>';
     output += '<td>' + data[count].post_title + '</td>';
     output += '<td>' + data[count].post_description + '</td>';
     output += '<td>' + data[count].date + '</td></tr>';
    }
    $('tbody').html(output);
   }
  })
 }

 $('#filter').click(function(){
  var from_date = $('#from_date').val();
  var to_date = $('#to_date').val();
  if(from_date != '' &&  to_date != '')
  {
   fetch_data(from_date, to_date);
  }
  else
  {
   alert('Both Date is required');
  }
 });

 $('#refresh').click(function(){
  $('#from_date').val('');
  $('#to_date').val('');
  fetch_data();
 });


});
</script>


Step 5 - Set Routes


Once you have completed working on code, lastly you have to set route of your controller method. For this you have to go to routes/web.php file. In this file you have to define your method route.


<?php

Route::get('/daterange', 'DateRangeController@index');
Route::post('/daterange/fetch_data', 'DateRangeController@fetch_data')->name('daterange.fetch_data');

?>


Once you have completed all above step, then you have to run your laravel application, for this you have to go to command prompt, and write following command.


php artisan serve


This command will start your laravel application, and you can access above by write followg url.


http://127.0.0.1:8000/daterange


So, this is complete step by step process for make date range search in Laravel using Ajax jQuery.


Friday, 15 February 2019

Make and Download Zip File using Codeigniter



In this post, We will discuss how can we generate zip file of multiple file, after this save in folder, lastly download generated zip file by using Codeigniter framework. Codeigniter is one of the best PHP framework, which will boost you web development process and there many web developer has been used this framework for their web application development, because it is widely popular PHP framework. It has provide many built in helper and library which will help you to develop your web application very fast. This framework will helps to do many task very easily. So, here also we have one task like how to make zip file in Codeigniter framework.

Codeigniter Zip Encoding Class


If you have use Codeigniter framework, then it is very easy for you to create Zip file. Because Codeigniter has it's own built in Zip library. This class will used for generate Zip archives, and that Zip archives we can download in our local computer also. Now how to initialze this zip class. For this we have to write following code.


$this->load->library('zip');


By using above code will can initialize Codeigniter Zip class, after this we can use different method of this class by calling $this->zip object. Now here we want to generate zip file of selected images from list of images. For this here we will use following method of this zip library.

read_file() - This method will read the content of a file and it will add into Zip.

add_data() - This method will add data to Zip file. In this define path of the file and data of this file.

archive() - This method will write file to the specified directory, in this method we have to define file name with complete path.

download() - This method will download created Zip file in our local computer, in this method we have to define zip file name.

Above all method of Codeigniter Zip class will help us to generate Zip file, save in folder and download in our local computer. Below you can find complete source code of this tutorial.




Make and Download Zip File using Codeigniter



Source Code


Zip_file.php(Controllers)



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

class Zip_file extends CI_Controller {
 
 function index()
 {
  $directory = 'download';
  $data["images"] = glob($directory . "/*.jpg");
  $this->load->view('zip_file', $data);
 }

 function download()
 {
  if($this->input->post('images'))
  {
   $this->load->library('zip');
   $images = $this->input->post('images');
   foreach($images as $image)
   {
    $this->zip->read_file($image);
   }
   $this->zip->download(''.time().'.zip');
  }
 }

}

?>





zip_file.php



<html>
<head>
    <title>How to Create ZIP File in CodeIgniter</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 box">
  <h3 align="center">How to Create ZIP File in CodeIgniter</h3>
  <br />
  <form method="post" action="<?php echo base_url(); ?>zip_file/download">
  <?php
  foreach($images as $image)
  {
   echo '
   <div class="col-md-2" align="center" style="margin-bottom:24px;">
    <img src="'.base_url().''.$image.'" class="img-thumbnail img-responsive" />
     <br />
    <input type="checkbox" name="images[]" class="select" value="'.$image.'" />
   </div>
   ';
  }
  ?>
  <br />
  <div align="center">
   <input type="submit" name="download" class="btn btn-primary" value="Download" />
  </div>
  </form>
 </div>
</body>
</html>

<script>
$(document).ready(function(){
 $('.select').click(function(){
  if(this.checked)
  {
   $(this).parent().css('border', '5px solid #ff0000');
  }
  else
  {
   $(this).parent().css('border', 'none');
  }
 });
});
</script>





Friday, 8 February 2019

Update or Edit Data using jQuery Dialogify with PHP Ajax



If you have use jQuery Dialogify plugin for create popup modal dialog box with your PHP web application. Then in that application you have to perform any update data operation. So, this post will help you to how to integrate jQuery Dialogify plugin for update or edit data operation using PHP with Ajax. In previous part, we have seen how can we use jquery Dialogify plugin for Insert or Add data into Mysql data using PHP with Ajax. For this things here we have use jQuery based Dialogify library for popup modal on web page. Because it is very easy to use, and it is light weight and simple plugin. For make modal dialog box, by using this plugin we have to not write any HTML code. It will allowed users to write callback function call on any event.

Here we want to update or edit data of existing mysql data using PHP script with Ajax. For load existing data into modal dialog box. If you have use this plugin, then you have to make seperate HTML form file for load data into form. Here for update or edit data, first we want to fetch existing data from database using Ajax request send to PHP. Once data has been received in json format, after this first we want to store that in Browser local storage using localStorage object, which store data with no any expiration date.

Once all data has been store in browser local storage using localStorage.setItem() method. By using this method we can store data in browser local storage. After storing all data now we have to go to seperate file in which we have create HTML form fields, and in that file, we have to fetch data from browser local storage using localStorage.getItem() method. By using this method we can fetch data from browser local storage and store into local variable. After fetching all data, after this we have to assign that data to html form fields using jquery code. Lastly we have to use new Dialogify() method, and make popup dialog box using seperate file form fields with fill data. So, when we have click on update button, then modal dialog will popup with fill form data. Lastly, we have to trigger ajax reqest when use click on Edit button, which send ajax request to PHP script for update of data. This whole process code will you can find below.




Update or Edit Data using jQuery Dialogify with PHP Ajax


Source Code


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_employee`
--

CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` text NOT NULL,
  `gender` varchar(10) NOT NULL,
  `designation` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `images` varchar(150) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_employee`
--

INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`, `images`) VALUES
(6, 'Barbra K. Hurley', '1241 Canis Heights Drive\r\nLos Angeles, CA 90017', 'Female', 'Service technician', 26, 'image_35.jpg'),
(7, 'Antonio J. Forbes', '403 Snyder Avenue\r\nCharlotte, NC 28208', 'Male', 'Faller', 28, 'image_36.jpg'),
(8, 'Charles D. Horst', '1636 Walnut Hill Drive\r\nCincinnati, OH 45202', 'Male', 'Financial investigator', 29, 'image_37.jpg'),
(174, 'Martha B. Tomlinson', '4005 Bird Spring Lane, Houston, TX 77002', 'Female', 'Systems programmer', 28, 'image_44.jpg'),
(162, 'Jarrod D. Jones', '3827 Bingamon Road, Garfield Heights, OH 44125', 'Male', 'Manpower development advisor', 24, 'image_3.jpg'),
(192, 'Flora Reed', '4000 Hamilton Drive Cambridge, MD 21613', 'Female', 'Machine offbearer', 27, 'image_41.jpg'),
(193, 'Donna Case', '4781 Apple Lane Peoria, IL 61602', 'Female', 'Machine operator', 26, 'image_15.jpg'),
(194, 'William Lewter', '168 Little Acres Lane Decatur, IL 62526', 'Male', 'Process engineer', 25, 'image_46.jpg'),
(195, 'Nathaniel Leger', '3200 Harley Brook Lane Meadville, PA 16335', 'Male', 'Nurse', 21, 'image_34.jpg'),
(183, 'Steve John', '108, Vile Parle, CL', 'Male', 'Software Engineer', 29, 'image_47.jpg'),
(186, 'Louis C. Charmis', '1462 Juniper Drive\r\nBreckenridge, MI 48612', 'Male', 'Mental health counselor', 30, ''),
(200, 'June Barnard', '4465 Woodland Terrace Folsom, CA 95630', 'Female', 'Fishing vessel operator', 24, '');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=206;


database_connection.php



<?php

//database_connection.php

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

?>


index.php



<html>
 <head>
  <title>Delete Mysql Data using jQuery Dialogify with PHP 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>
  <script src="https://www.jqueryscript.net/demo/Dialog-Modal-Dialogify/dist/dialogify.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Delete Mysql Data using jQuery Dialogify with PHP Ajax</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-6">
       <h3 class="panel-title">Employee Data</h3>
      </div>
      <div class="col-md-6" align="right">
       <button type="button" name="add_data" id="add_data" class="btn btn-success btn-xs">Add</button>
      </div>
     </div>
    </div>
    <div class="panel-body">
     <div class="table-responsive">
      <span id="form_response"></span>
      <table id="user_data" class="table table-bordered table-striped">
       <thead>
        <tr>
         <td>Name</td>
         <td>Gender</td>
         <td>Designation</td>
         <td>Age</td>
         <td>View</td>
         <td>Edit</td>
         <td>Delete</td>
        </tr>
       </thead>
      </table>      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script type="text/javascript" language="javascript" >
$(document).ready(function(){
 
 var dataTable = $('#user_data').DataTable({
  "processing":true,
  "serverSide":true,
  "order":[],
  "ajax":{
   url:"fetch.php",
   type:"POST"
  },
  "columnDefs":[
   {
    "targets":[4,5,6],
    "orderable":false,
   },
  ],

 });

 $(document).on('click', '.view', function(){
  var id = $(this).attr('id');
  var options = {
   ajaxPrefix: '',
   ajaxData: {id:id},
   ajaxComplete:function(){
    this.buttons([{
     type: Dialogify.BUTTON_PRIMARY
    }]);
   }
  };
  new Dialogify('fetch_single.php', options)
   .title('View Employee Details')
   .showModal();
 });
 
 $('#add_data').click(function(){
  var options = {
   ajaxPrefix:''
  };
  new Dialogify('add_data_form.php', options)
   .title('Add New Employee Data')
   .buttons([
    {
     text:'Cancle',
     click:function(e){
      this.close();
     }
    },
    {
     text:'Insert',
     type:Dialogify.BUTTON_PRIMARY,
     click:function(e)
     {
      var image_data = $('#images').prop("files")[0];
      var form_data = new FormData();
      form_data.append('images', image_data);
      form_data.append('name', $('#name').val());
      form_data.append('address', $('#address').val());
      form_data.append('gender', $('#gender').val());
      form_data.append('designation', $('#designation').val());
      form_data.append('age', $('#age').val());
      $.ajax({
       method:"POST",
       url:'insert_data.php',
       data:form_data,
       dataType:'json',
       contentType:false,
       cache:false,
       processData:false,
       success:function(data)
       {
        if(data.error != '')
        {
         $('#form_response').html('<div class="alert alert-danger">'+data.error+'</div>');
        }
        else
        {
         $('#form_response').html('<div class="alert alert-success">'+data.success+'</div>');
         dataTable.ajax.reload();
        }
       }
      });
     }
    }
   ]).showModal();
 });

 $(document).on('click', '.update', function(){
  var id = $(this).attr('id');
  $.ajax({
   url:"fetch_single_data.php",
   method:"POST",
   data:{id:id},
   dataType:'json',
   success:function(data)
   {
    localStorage.setItem('name', data[0].name);
    localStorage.setItem('address', data[0].address);
    localStorage.setItem('gender', data[0].gender);
    localStorage.setItem('designation', data[0].designation);
    localStorage.setItem('age', data[0].age);
    localStorage.setItem('images', data[0].images);

    var options = {
     ajaxPrefix:''
    };
    new Dialogify('edit_data_form.php', options)
     .title('Edit Employee Data')
     .buttons([
      {
       text:'Cancle',
       click:function(e){
        this.close();
       }
      },
      {
       text:'Edit',
       type:Dialogify.BUTTON_PRIMARY,
       click:function(e)
       {
        var image_data = $('#images').prop("files")[0];
        var form_data = new FormData();
        form_data.append('images', image_data);
        form_data.append('name', $('#name').val());
        form_data.append('address', $('#address').val());
        form_data.append('gender', $('#gender').val());
        form_data.append('designation', $('#designation').val());
        form_data.append('age', $('#age').val());
        form_data.append('hidden_images', $('#hidden_images').val());
        form_data.append('id', data[0].id);
        $.ajax({
         method:"POST",
         url:'update_data.php',
         data:form_data,
         dataType:'json',
         contentType:false,
         cache:false,
         processData:false,
         success:function(data)
         {
          if(data.error != '')
          {
           $('#form_response').html('<div class="alert alert-danger">'+data.error+'</div>');
          }
          else
          {
           $('#form_response').html('<div class="alert alert-success">'+data.success+'</div>');
           dataTable.ajax.reload();
          }
         }
        });
       }
      }
     ]).showModal();
   }
  })
 });

 $(document).on('click', '.delete', function(){
  var id = $(this).attr('id');
  Dialogify.confirm("<h3 class='text-danger'><b>Are you sure you want to remove this data?</b></h3>", {
   ok:function(){
    $.ajax({
     url:"delete_data.php",
     method:"POST",
     data:{id:id},
     success:function(data)
     {
      Dialogify.alert('<h3 class="text-success text-center"><b>Data has been deleted</b></h3>');
      dataTable.ajax.reload();
     }
    })
   },
   cancel:function(){
    this.close();
   }
  });
 });
 
 
});
</script>


fetch.php



<?php

//fetch.php

include('database_connection.php');
$query = '';
$output = array();
$query .= "SELECT * FROM tbl_employee ";
if(isset($_POST["search"]["value"]))
{
 $query .= 'WHERE name LIKE "%'.$_POST["search"]["value"].'%" OR address LIKE "%'.$_POST["search"]["value"].'%" OR gender LIKE "%'.$_POST["search"]["value"].'%" OR designation LIKE "%'.$_POST["search"]["value"].'%" OR age LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
 $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
 $query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1)
{
 $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
 $sub_array = array();
 $sub_array[] = $row["name"];
 $sub_array[] = $row["gender"];
 $sub_array[] = $row["designation"];
 $sub_array[] = $row["age"];
 $sub_array[] = '<button type="button" name="view" id="'.$row["id"].'" class="btn btn-primary btn-xs view">View</button>';
 $sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-warning btn-xs update">Update</button>';
 $sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-xs delete">Delete</button>';
 $data[] = $sub_array;
}

function get_total_all_records($connect)
{
 $statement = $connect->prepare("SELECT * FROM tbl_employee");
 $statement->execute();
 $result = $statement->fetchAll();
 return $statement->rowCount();
}

$output = array(
 "draw"    => intval($_POST["draw"]),
 "recordsTotal"  =>  $filtered_rows,
 "recordsFiltered" => get_total_all_records($connect),
 "data"    => $data
);
echo json_encode($output);
?>


add_data_form.php



<div class="form-group">
 <label>Enter Employee Name</label>
 <input type="text" name="name" id="name" class="form-control" />
</div>
<div class="form-group">
 <label>Enter Employee Address</label>
 <textarea name="address" id="address" class="form-control"></textarea>
</div>
<div class="form-group">
 <label>Enter Employee Gender</label>
 <select name="gender" id="gender" class="form-control">
  <option value="Male">Male</option>
  <option value="Female">Female</option>
 </select>
</div>
<div class="form-group">
 <label>Enter Employee Desingation</label>
 <input type="text" name="designation" id="designation" class="form-control" />
</div>
<div class="form-group">
 <label>Enter Employee Age</label>
 <input type="text" name="age" id="age" class="form-control" />
</div>
<div class="form-group">
 <label>Select Employee Image</label>
 <input type="file" name="images" id="images" />
</div>


insert_data.php



<?php

//insert_data.php

include('database_connection.php');

if(isset($_POST["name"]))
{
 $error = '';
 $success = '';
 $name = '';
 $address = '';
 $designation = '';
 $age = '';
 $images = '';
 $gender = $_POST["gender"];
 if(empty($_POST["name"]))
 {
  $error .= '<p>Name is Required</p>';
 }
 else
 {
  $name = $_POST["name"];
 }
 if(empty($_POST["address"]))
 {
  $error .= '<p>Address is Required</p>';
 }
 else
 {
  $address = $_POST["address"];
 }
 if(empty($_POST["designation"]))
 {
  $error .= '<p>Designation is Required</p>';
 }
 else
 {
  $designation = $_POST["designation"];
 }
 if(empty($_POST["age"]))
 {
  $error .= '<p>Age is Required</p>';
 }
 else
 {
  $age = $_POST["age"];
 }

 if(isset($_FILES["images"]["name"]) && $_FILES["images"]["name"] != '')
 {
  $image_name = $_FILES["images"]["name"];
  $array = explode(".", $image_name);
  $extension = end($array);
  $temporary_name = $_FILES["images"]["tmp_name"];
  $allowed_extension = array("jpg","png");
  if(!in_array($extension, $allowed_extension))
  {
   $error .= '<p>Invalid Image</p>';
  }
  else
  {
   $images = rand() . '.' . $extension;
   move_uploaded_file($temporary_name, 'images/' . $images);
  }
 }
 if($error == '')
 {
  $data = array(
   ':name'   => $name,
   ':address'  => $address,
   ':gender'  => $gender,
   ':designation' => $designation,
   ':age'   => $age,
   ':images'  => $images
  );

  $query = "
  INSERT INTO tbl_employee 
  (name, address, gender, designation, age, images) 
  VALUES (:name, :address, :gender, :designation, :age, :images)
  ";
  $statement = $connect->prepare($query);
  $statement->execute($data);
  $success = 'Employee Data Inserted';
 }
 $output = array(
  'success'  => $success,
  'error'   => $error
 );
 echo json_encode($output);
}

?>







fetch_single_data.php



<?php

//fetch_single_data.php

include('database_connection.php');

if(isset($_POST["id"]))
{
 $query = "
 SELECT * FROM tbl_employee WHERE id = '".$_POST["id"]."'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 while($row = $statement->fetch(PDO::FETCH_ASSOC))
 {
  $data[] = $row;
 }
 echo json_encode($data);
}

?>


edit_data_form.php



<div class="form-group">
 <label>Enter Employee Name</label>
 <input type="text" name="name" id="name" class="form-control" />
</div>
<div class="form-group">
 <label>Enter Employee Address</label>
 <textarea name="address" id="address" class="form-control"></textarea>
</div>
<div class="form-group">
 <label>Enter Employee Gender</label>
 <select name="gender" id="gender" class="form-control">
  <option value="Male">Male</option>
  <option value="Female">Female</option>
 </select>
</div>
<div class="form-group">
 <label>Enter Employee Desingation</label>
 <input type="text" name="designation" id="designation" class="form-control" />
</div>
<div class="form-group">
 <label>Enter Employee Age</label>
 <input type="text" name="age" id="age" class="form-control" />
</div>
<div class="form-group">
 <label>Select Employee Image</label>
 <input type="file" name="images" id="images" />
 <span id="uploaded_image"></span>
 <input type="hidden" name="hidden_images" id="hidden_images" />
</div>

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

  var name = localStorage.getItem('name');
  var address = localStorage.getItem('address');
  var gender = localStorage.getItem('gender');
  var designation = localStorage.getItem('designation');
  var age = localStorage.getItem('age');
  var images = localStorage.getItem('images');

  $('#name').val(name);
  $('#address').val(address);
  $('#gender').val(gender);
  $('#designation').val(designation);
  $('#age').val(age);

  if(images != '')
  {
   $('#uploaded_image').html('<img src="images/'+images+'" class="img-thumbnail" width="100" />');
   $('#hidden_images').val(images);
  }

 });
</script>


update_data.php



<?php

//update_data.php

include('database_connection.php');

if(isset($_POST["name"]))
{
 $error = '';
 $success = '';
 $name = '';
 $address = '';
 $designation = '';
 $age = '';
 $images = '';
 $gender = $_POST["gender"];
 if(empty($_POST["name"]))
 {
  $error .= '<p>Name is Required</p>';
 }
 else
 {
  $name = $_POST["name"];
 }
 if(empty($_POST["address"]))
 {
  $error .= '<p>Address is Required</p>';
 }
 else
 {
  $address = $_POST["address"];
 }
 if(empty($_POST["designation"]))
 {
  $error .= '<p>Designation is Required</p>';
 }
 else
 {
  $designation = $_POST["designation"];
 }
 if(empty($_POST["age"]))
 {
  $error .= '<p>Age is Required</p>';
 }
 else
 {
  $age = $_POST["age"];
 }

 $images = $_POST['hidden_images'];

 if(isset($_FILES["images"]["name"]) && $_FILES["images"]["name"] != '')
 {
  $image_name = $_FILES["images"]["name"];
  $array = explode(".", $image_name);
  $extension = end($array);
  $temporary_name = $_FILES["images"]["tmp_name"];
  $allowed_extension = array("jpg","png");
  if(!in_array($extension, $allowed_extension))
  {
   $error .= '<p>Invalid Image</p>';
  }
  else
  {
   $images = rand() . '.' . $extension;
   move_uploaded_file($temporary_name, 'images/' . $images);
  }
 }
 if($error == '')
 {
  $data = array(
   ':name'   => $name,
   ':address'  => $address,
   ':gender'  => $gender,
   ':designation' => $designation,
   ':age'   => $age,
   ':images'  => $images,
   ':id'   => $_POST["id"]
  );

  $query = "
  UPDATE tbl_employee 
  SET name = :name,
  address = :address,
  gender = :gender, 
  designation = :designation, 
  age = :age, 
  images = :images 
  WHERE id = :id
  ";
  $statement = $connect->prepare($query);
  $statement->execute($data);
  $success = 'Employee Data Updated';
 }
 $output = array(
  'success'  => $success,
  'error'   => $error
 );
 echo json_encode($output);
}

?>





delete_data.php



<?php

//delete_data.php

include('database_connection.php');

if(isset($_POST["id"]))
{
 $query = "
 DELETE FROM tbl_employee 
 WHERE id = '".$_POST["id"]."'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
}

?>


Here we have provide complete source code with View data in modal dialog box, insert data, update data and delete data using jQuery Dialogify plugin using PHP with Ajax.


Tuesday, 5 February 2019

Insert or Add Data using jQuery Dialogify with PHP Ajax


This is second post on jQuery Dialogify plugin with PHP. And in this post we will discuss how to use jQuery Dialogify Plugin for insert or add data into Mysql table using PHP with Ajax. In previous post we have seen how to load dynamic mysql data into pop up dialog box using jQuery Dialogify plugin with PHP Ajax. Inserting of Data is a basic function of any application. If you want to make single page CRUD application then you have to perform all CRUD option on same page without going to another page. For do all operation on Single page you have to make form for insert data in pop up modal dialog box.

For make pop up dialog box, In one of our tutorial in which we have use Bootstrap modal for use Insert data with PHP Ajax. By using Bootstrap modal we can make pop up modal dialog box. But now we want to use jQuery Dialogify plugin for make pop up dialog box, and in this modal dialog box we want to make insert data form. Here we will not only insert data into mysql table but also we will also upload image also with data insertion. So, here we have use jquery Dialogify plugin for insert data with upload file also using PHP with Ajax. So, with jQuery Dialogify plugin we cannot make form under pop up dialog box directly.

How to make Form in jQuery Dialogify Plugin


If we have use jQuery Dialogify Plugin for insert data then for insert data we have to make form for submit data to server. But in this plugin we cannot directly make form in pop up dialog box, but for make form, we have to define form fields in some other php file. In that file we have to just define form field, this plugin will automatically add form tag. Now the question arise how other php file form will be append into jQuery Dialogify pop up modal. For this we have to write new Dialogify() method, and under this method we have to define php file in which we have define form field. This method will pop up modal dialog box with form fields, which has been define php file. Below you can find complete source code of how to use jQuery Dialogify plugin for insert or add data into mysql using PHP with Ajax.



Insert or Add Data using jQuery Dialogify with PHP Ajax




Source Code


Database



--
-- Table structure for table `tbl_employee`
--

CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` text NOT NULL,
  `gender` varchar(10) NOT NULL,
  `designation` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `images` varchar(150) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_employee`
--

INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`, `images`) VALUES
(6, 'Barbra K. Hurley', '1241 Canis Heights Drive\r\nLos Angeles, CA 90017', 'Female', 'Service technician', 26, 'image_35.jpg'),
(7, 'Antonio J. Forbes', '403 Snyder Avenue\r\nCharlotte, NC 28208', 'Male', 'Faller', 28, 'image_36.jpg'),
(8, 'Charles D. Horst', '1636 Walnut Hill Drive\r\nCincinnati, OH 45202', 'Male', 'Financial investigator', 29, 'image_37.jpg'),
(174, 'Martha B. Tomlinson', '4005 Bird Spring Lane, Houston, TX 77002', 'Female', 'Systems programmer', 28, 'image_44.jpg'),
(162, 'Jarrod D. Jones', '3827 Bingamon Road, Garfield Heights, OH 44125', 'Male', 'Manpower development advisor', 24, 'image_3.jpg'),
(192, 'Flora Reed', '4000 Hamilton Drive Cambridge, MD 21613', 'Female', 'Machine offbearer', 27, 'image_41.jpg'),
(193, 'Donna Case', '4781 Apple Lane Peoria, IL 61602', 'Female', 'Machine operator', 26, 'image_15.jpg'),
(194, 'William Lewter', '168 Little Acres Lane Decatur, IL 62526', 'Male', 'Process engineer', 25, 'image_46.jpg'),
(195, 'Nathaniel Leger', '3200 Harley Brook Lane Meadville, PA 16335', 'Male', 'Nurse', 21, 'image_34.jpg'),
(183, 'Steve John', '108, Vile Parle, CL', 'Male', 'Software Engineer', 29, 'image_47.jpg'),
(186, 'Louis C. Charmis', '1462 Juniper Drive\r\nBreckenridge, MI 48612', 'Male', 'Mental health counselor', 30, ''),
(200, 'June Barnard', '4465 Woodland Terrace Folsom, CA 95630', 'Female', 'Fishing vessel operator', 24, '');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=206;


database_connection.php



<?php

//database_connection.php

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

?>



<html>
 <head>
  <title>Insert or Add Data using jQuery Dialogify with PHP 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>
  <script src="https://www.jqueryscript.net/demo/Dialog-Modal-Dialogify/dist/dialogify.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Insert or Add Data using jQuery Dialogify with PHP Ajax</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-6">
       <h3 class="panel-title">Employee Data</h3>
      </div>
      <div class="col-md-6" align="right">
       <button type="button" name="add_data" id="add_data" class="btn btn-success btn-xs">Add</button>
      </div>
     </div>
    </div>
    <div class="panel-body">
     <div class="table-responsive">
      <span id="form_response"></span>
      <table id="user_data" class="table table-bordered table-striped">
       <thead>
        <tr>
         <td>Name</td>
         <td>Gender</td>
         <td>Designation</td>
         <td>Age</td>
         <td>View</td>
        </tr>
       </thead>
      </table>
      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script type="text/javascript" language="javascript" >
$(document).ready(function(){
 
 var dataTable = $('#user_data').DataTable({
  "processing":true,
  "serverSide":true,
  "order":[],
  "ajax":{
   url:"fetch.php",
   type:"POST"
  },
  "columnDefs":[
   {
    "targets":[4],
    "orderable":false,
   },
  ],

 });

 $(document).on('click', '.view', function(){
  var id = $(this).attr('id');
  var options = {
   ajaxPrefix: '',
   ajaxData: {id:id},
   ajaxComplete:function(){
    this.buttons([{
     type: Dialogify.BUTTON_PRIMARY
    }]);
   }
  };
  new Dialogify('fetch_single.php', options)
   .title('View Employee Details')
   .showModal();
 });
 
 $('#add_data').click(function(){
  var options = {
   ajaxPrefix:''
  };
  new Dialogify('add_data_form.php', options)
   .title('Add New Employee Data')
   .buttons([
    {
     text:'Cancle',
     click:function(e){
      this.close();
     }
    },
    {
     text:'Insert',
     type:Dialogify.BUTTON_PRIMARY,
     click:function(e)
     {
      var image_data = $('#images').prop("files")[0];
      var form_data = new FormData();
      form_data.append('images', image_data);
      form_data.append('name', $('#name').val());
      form_data.append('address', $('#address').val());
      form_data.append('gender', $('#gender').val());
      form_data.append('designation', $('#designation').val());
      form_data.append('age', $('#age').val());
      $.ajax({
       method:"POST",
       url:'insert_data.php',
       data:form_data,
       dataType:'json',
       contentType:false,
       cache:false,
       processData:false,
       success:function(data)
       {
        if(data.error != '')
        {
         $('#form_response').html('<div class="alert alert-danger">'+data.error+'</div>');
        }
        else
        {
         $('#form_response').html('<div class="alert alert-success">'+data.success+'</div>');
         dataTable.ajax.reload();
        }
       }
      });
     }
    }
   ]).showModal();
 });
 
 
});
</script>


fetch.php



<?php

//fetch.php

include('database_connection.php');
$query = '';
$output = array();
$query .= "SELECT * FROM tbl_employee ";
if(isset($_POST["search"]["value"]))
{
 $query .= 'WHERE name LIKE "%'.$_POST["search"]["value"].'%" OR address LIKE "%'.$_POST["search"]["value"].'%" OR gender LIKE "%'.$_POST["search"]["value"].'%" OR designation LIKE "%'.$_POST["search"]["value"].'%" OR age LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
 $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
 $query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1)
{
 $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
 $sub_array = array();
 $sub_array[] = $row["name"];
 $sub_array[] = $row["gender"];
 $sub_array[] = $row["designation"];
 $sub_array[] = $row["age"];
 $sub_array[] = '<button type="button" name="view" id="'.$row["id"].'" class="btn btn-primary btn-xs view">View</button>';
 $data[] = $sub_array;
}

function get_total_all_records($connect)
{
 $statement = $connect->prepare("SELECT * FROM tbl_employee");
 $statement->execute();
 $result = $statement->fetchAll();
 return $statement->rowCount();
}

$output = array(
 "draw"    => intval($_POST["draw"]),
 "recordsTotal"  =>  $filtered_rows,
 "recordsFiltered" => get_total_all_records($connect),
 "data"    => $data
);
echo json_encode($output);
?>


fetch_single.php



<?php

//fetch_single.php

include('database_connection.php');

if(isset($_GET["id"]))
{
 $query = "SELECT * FROM tbl_employee WHERE id = '".$_GET["id"]."'";

 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '<div class="row">';
 foreach($result as $row)
 {
  $images = '';
  if($row["images"] != '')
  {
   $images = '<img src="images/'.$row["images"].'" class="img-responsive img-thumbnail" />';
  }
  else
  {
   $images = '<img src="https://www.gravatar.com/avatar/38ed5967302ec60ff4417826c24feef6?s=80&d=mm&r=g" class="img-responsive img-thumbnail" />';
  }
  $output .= '
  <div class="col-md-3">
   <br />
   '.$images.'
  </div>
  <div class="col-md-9">
   <br />
   <p><label>Name :&nbsp;</label>'.$row["name"].'</p>
   <p><label>Address :&nbsp;</label>'.$row["address"].'</p>
   <p><label>Gender :&nbsp;</label>'.$row["gender"].'</p>
   <p><label>Designation :&nbsp;</label>'.$row["designation"].'</p>
   <p><label>Age :&nbsp;</label>'.$row["age"].' years</p>
  </div>
  </div><br />
  ';
 }
 echo $output;
}

?>







add_data_form.php



<div class="form-group">
 <label>Enter Employee Name</label>
 <input type="text" name="name" id="name" class="form-control" />
</div>
<div class="form-group">
 <label>Enter Employee Address</label>
 <textarea name="address" id="address" class="form-control"></textarea>
</div>
<div class="form-group">
 <label>Enter Employee Gender</label>
 <select name="gender" id="gender" class="form-control">
  <option value="Male">Male</option>
  <option value="Female">Female</option>
 </select>
</div>
<div class="form-group">
 <label>Enter Employee Desingation</label>
 <input type="text" name="designation" id="designation" class="form-control" />
</div>
<div class="form-group">
 <label>Enter Employee Age</label>
 <input type="text" name="age" id="age" class="form-control" />
</div>
<div class="form-group">
 <label>Select Employee Image</label>
 <input type="file" name="images" id="images" />
</div>


insert_data.php



<?php

//insert_data.php

include('database_connection.php');

if(isset($_POST["name"]))
{
 $error = '';
 $success = '';
 $name = '';
 $address = '';
 $designation = '';
 $age = '';
 $images = '';
 $gender = $_POST["gender"];
 if(empty($_POST["name"]))
 {
  $error .= '<p>Name is Required</p>';
 }
 else
 {
  $name = $_POST["name"];
 }
 if(empty($_POST["address"]))
 {
  $error .= '<p>Address is Required</p>';
 }
 else
 {
  $address = $_POST["address"];
 }
 if(empty($_POST["designation"]))
 {
  $error .= '<p>Designation is Required</p>';
 }
 else
 {
  $designation = $_POST["designation"];
 }
 if(empty($_POST["age"]))
 {
  $error .= '<p>Age is Required</p>';
 }
 else
 {
  $age = $_POST["age"];
 }

 if(isset($_FILES["images"]["name"]) && $_FILES["images"]["name"] != '')
 {
  $image_name = $_FILES["images"]["name"];
  $array = explode(".", $image_name);
  $extension = end($array);
  $temporary_name = $_FILES["images"]["tmp_name"];
  $allowed_extension = array("jpg","png");
  if(!in_array($extension, $allowed_extension))
  {
   $error .= '<p>Invalid Image</p>';
  }
  else
  {
   $images = rand() . '.' . $extension;
   move_uploaded_file($temporary_name, 'images/' . $images);
  }
 }
 if($error == '')
 {
  $data = array(
   ':name'   => $name,
   ':address'  => $address,
   ':gender'  => $gender,
   ':designation' => $designation,
   ':age'   => $age,
   ':images'  => $images
  );

  $query = "
  INSERT INTO tbl_employee 
  (name, address, gender, designation, age, images) 
  VALUES (:name, :address, :gender, :designation, :age, :images)
  ";
  $statement = $connect->prepare($query);
  $statement->execute($data);
  $success = 'Employee Data Inserted';
 }
 $output = array(
  'success'  => $success,
  'error'   => $error
 );
 echo json_encode($output);
}

?>


This is combine source code of View Dyanmic Data using Dialogify plugin post and Insert Data using Dialogify with PHP Ajax. If you have any query regarding this post, you can send your query via comment.