Thursday, 26 April 2018

Multi Select Dynamic Dependent Select box using PHP Ajax



Hi, In this post we have implement multi select dynamic dropdown list box by using PHP with Ajax. Dynamic dependent select box means child select box data has been depend on value of parent select box. But this is single option dropdown list box and in which we can select only single option and based on selected option value it will load data in child load. But in web development we want to required to select multiple option from select box and based on that selected option we want to load data related to selected multiple option in child selectbox. For this we have make this tutorial.

For make multi select dynamic dependent select box using PHP with Ajax, we have use Bootstrap Multiselect plugin. This is a plugin for jQuery and Bootstrap which allows the user to select multiple options by checked on checkboxes. Here we will make multiple select dropdown listbox by using Bootstrap Multiselect plugin. Here we will make three different multi select dropdown listbox. So, when page has been load into browser then only first level select box has been filled with data and both child select box has been blank, so when we have select option from first selectbox option then selected of multiple option value, it will load data into second level category data which connected with value of first level category value with out refresh of web page. Same way when we have select multiple option from second level category option, then in third level category dropdown will be filled with data on the basis on selection of option from second level dropdown list. This way it this script will work.

Here we have use simple PHP script with Ajax and for make multiple selection dropdown listbox we have use Bootstrap Multiselect plugin. If you have know single selection dynamic dependent selectbox then you get better idea regarding this tutorial. In which we can select multiple option in parent select box and child dropdown listbox will be filled with data based on value of option selection in parent select box.








Source Code


database_connection.php



<?php

//database_connection.php

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

?>


index.php



<?php

//index.php

include('database_connection.php');

$query = "
SELECT * FROM first_level_category 
ORDER BY first_level_category_name ASC
";

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

$statement->execute();

$result = $statement->fetchAll();

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Bootstrap Multi Select Dynamic Dependent Select box using PHP 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.5/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" />
 </head>
 <body>
  <br />
  <div class="container">
   <h2 align="center">Multi Select Dynamic Dependent Select box using PHP Ajax</h2>
   <br /><br />
   <div style="width: 500px; margin:0 auto">
    <div class="form-group">
     <label>First Level Category</label><br />
     <select id="first_level" name="first_level[]" multiple class="form-control">
     <?php
     foreach($result as $row)
     {
      echo '<option value="'.$row["first_level_category_id"].'">'.$row["first_level_category_name"].'</option>';
     }
     ?>
     </select>
    </div>
    <div class="form-group">
     <label>Second Level Category</label><br />
     <select id="second_level" name="second_level[]" multiple class="form-control">

     </select>
    </div>
    <div class="form-group">
     <label>Third Level Category</label><br />
     <select id="third_level" name="third_level[]" multiple class="form-control">

     </select>
    </div>
   </div>
  </div>
 </body>
</html>
<script>
$(document).ready(function(){

 $('#first_level').multiselect({
  nonSelectedText:'Select First Level Category',
  buttonWidth:'400px',
  onChange:function(option, checked){
   $('#second_level').html('');
   $('#second_level').multiselect('rebuild');
   $('#third_level').html('');
   $('#third_level').multiselect('rebuild');
   var selected = this.$select.val();
   if(selected.length > 0)
   {
    $.ajax({
     url:"fetch_second_level_category.php",
     method:"POST",
     data:{selected:selected},
     success:function(data)
     {
      $('#second_level').html(data);
      $('#second_level').multiselect('rebuild');
     }
    })
   }
  }
 });

 $('#second_level').multiselect({
  nonSelectedText: 'Select Second Level Category',
  buttonWidth:'400px',
  onChange:function(option, checked)
  {
   $('#third_level').html('');
   $('#third_level').multiselect('rebuild');
   var selected = this.$select.val();
   if(selected.length > 0)
   {
    $.ajax({
     url:"fetch_third_level_category.php",
     method:"POST",
     data:{selected:selected},
     success:function(data)
     {
      $('#third_level').html(data);
      $('#third_level').multiselect('rebuild');
     }
    });
   }
  }
 });

 $('#third_level').multiselect({
  nonSelectedText: 'Select Third Level Category',
  buttonWidth:'400px'
 });

});
</script>


fetch_second_level_category.php



<?php

//fetch_second_level_category.php

include('database_connection.php');

if(isset($_POST["selected"]))
{
 $id = join("','", $_POST["selected"]);
 $query = "
 SELECT * FROM second_level_category 
 WHERE first_level_category_id IN ('".$id."')
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '';
 foreach($result as $row)
 {
  $output .= '<option value="'.$row["second_level_category_id"].'">'.$row["second_level_category_name"].'</option>';
 }
 echo $output;
}

?>


fetch_third_level_category.php



<?php

//fetch_third_level_category.php

include('database_connection.php');

if(isset($_POST["selected"]))
{
 $id = join("','", $_POST["selected"]);
 $query = "
 SELECT * FROM third_level_category 
 WHERE second_level_category_id IN ('".$id."')
 "; 
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '';
 foreach($result as $row)
 {
  $output .= '<option value="'.$row["third_level_category_id"].'">'.$row["third_level_category_name"].'</option>';
 }
 echo $output;
}




?>


Database



--
-- Database: `test`
--

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

--
-- Table structure for table `first_level_category`
--

CREATE TABLE `first_level_category` (
  `first_level_category_id` int(11) NOT NULL,
  `first_level_category_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `first_level_category`
--

INSERT INTO `first_level_category` (`first_level_category_id`, `first_level_category_name`) VALUES
(1, 'Electronics & Electrical'),
(2, 'Apparel & Garments'),
(3, 'Automobile Parts'),
(4, 'Construction Material');

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

--
-- Table structure for table `second_level_category`
--

CREATE TABLE `second_level_category` (
  `second_level_category_id` int(11) NOT NULL,
  `first_level_category_id` int(11) NOT NULL,
  `second_level_category_name` varchar(300) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `second_level_category`
--

INSERT INTO `second_level_category` (`second_level_category_id`, `first_level_category_id`, `second_level_category_name`) VALUES
(1, 1, 'Audio Video Equipment'),
(2, 1, 'Water Heater'),
(3, 1, 'Air Conditioner'),
(4, 2, 'Children Clothing'),
(5, 2, 'Women Wear'),
(6, 2, 'Men Wear'),
(7, 3, 'Auto Parts'),
(8, 3, 'Auto Accessories'),
(9, 3, 'Auto Electronics'),
(10, 4, 'Tiles'),
(11, 4, 'Plywood'),
(12, 4, 'Sanitaryware');

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

--
-- Table structure for table `third_level_category`
--

CREATE TABLE `third_level_category` (
  `third_level_category_id` int(11) NOT NULL,
  `second_level_category_id` int(11) NOT NULL,
  `third_level_category_name` varchar(300) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `third_level_category`
--

INSERT INTO `third_level_category` (`third_level_category_id`, `second_level_category_id`, `third_level_category_name`) VALUES
(1, 1, 'Mini FM Radio'),
(2, 1, 'LCD TV'),
(3, 1, 'Music Player'),
(4, 2, 'Solar Water Heater'),
(5, 2, 'Thermic Fluid Heater'),
(6, 2, 'Portable Water Heater'),
(7, 3, 'Portable Air Conditioner'),
(8, 3, 'Air Conditioner Part'),
(9, 3, 'Commercial Air Conditioner'),
(10, 4, 'Baby Clothes'),
(11, 4, 'Kids Garments'),
(12, 4, 'Designer Clothes'),
(13, 5, 'Legging'),
(14, 5, 'Ladies Fashion Garments'),
(15, 5, 'Gown Dresses'),
(16, 6, 'Men Formal Wear'),
(17, 6, 'Mens Kurtas'),
(18, 6, 'Mens Lower'),
(19, 7, 'Car Shock Absorber'),
(20, 7, 'Glass Cleaning Wiper'),
(21, 7, 'Steering Lock'),
(22, 8, 'Grille Light'),
(23, 8, 'Automobile Couplings'),
(24, 8, 'Motorcycle Helmet'),
(25, 9, 'Car Audio System'),
(26, 9, 'Car Lcd'),
(27, 9, 'Car Stereos'),
(28, 10, 'Stone Tiles'),
(29, 10, 'Zig Zag Tiles'),
(30, 10, 'Granite Tiles'),
(31, 11, 'Flexible Plywood'),
(32, 11, 'Designer Plywood'),
(33, 11, 'Commercial Plywood'),
(34, 12, 'Brass Sanitary Fittings'),
(35, 12, 'Porcelain Toilet'),
(36, 12, 'Lavatory Basin'),
(37, 12, 'Kitchen Sink');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `first_level_category`
--
ALTER TABLE `first_level_category`
  ADD PRIMARY KEY (`first_level_category_id`);

--
-- Indexes for table `second_level_category`
--
ALTER TABLE `second_level_category`
  ADD PRIMARY KEY (`second_level_category_id`);

--
-- Indexes for table `third_level_category`
--
ALTER TABLE `third_level_category`
  ADD PRIMARY KEY (`third_level_category_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `first_level_category`
--
ALTER TABLE `first_level_category`
  MODIFY `first_level_category_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

--
-- AUTO_INCREMENT for table `second_level_category`
--
ALTER TABLE `second_level_category`
  MODIFY `second_level_category_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;

--
-- AUTO_INCREMENT for table `third_level_category`
--
ALTER TABLE `third_level_category`
  MODIFY `third_level_category_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=38;

Tuesday, 24 April 2018

How to Use Jquery Datatable with AngularJS & PHP


We all know Jquery Datatables plugin is a high level premium jquery plugin which will convert simple HTML table data into tabular grid format. In previous, in one of our web tutorial which we have publish on JQuery Datatables Server Side Processing in PHP and we have received very huge response from our site viewer and they have requested us to make tutorial on Jquery Datatables server side processing by using AngularJS Datatable with PHP. Because Angular Datatable is one of the angular module which has been provide only datatable directive but also datatable options and helpers. With the help of Angular Datatables module, we can make stylish tabular grid listing in our angular web application with functionality like pagination, searching, sorting etc. So here in this post we will discuss on topic like Angular Datatables server side processing with PHP script and MySQL database. In this post we have not only covered tutorial in easy steps but also you can find video tutorial, live demo and source code on how to use jquery datatables plugin with AngularJS and PHP.







Following is the file structure of this tutorial source code.

  • index.html
  • fetch.php

Step 1 - Create Database with Data


Here we have covered topic on JQuery Datatables Server Side processing using AngularJs PHP, for this first we have to create customer table and and insert some customer data into table table.


--
-- Database: `test`
--

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

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

CREATE TABLE `tbl_customer` (
  `CustomerID` int(11) NOT NULL,
  `CustomerName` varchar(250) 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;

--
-- Dumping data for table `tbl_customer`
--

INSERT INTO `tbl_customer` (`CustomerID`, `CustomerName`, `Address`, `City`, `PostalCode`, `Country`) VALUES
(1, 'Willie Whited', '2524 White River Way', 'Salt Lake City', '84106', 'USA'),
(2, 'Lisa Squires', 'Fehringer Strasse 27', 'MARIA BUCH', '8750', 'Austria'),
(3, 'Sean Patterson', 'Rue des Ecoles 426', 'Vlierzele', '9520', 'Belgium'),
(4, 'Anna Scott', 'Rua C 66, 1384', 'Goiania-GO', '74305-450', 'Brazil'),
(5, 'Desmond Peterson', '1414 Grey Rd', 'Feversham', 'ON N0C 1C0', 'Canada'),
(6, 'Samuel Hogan', '13, Avenue De Marlioz', 'ARGENTEUIL', '95100', 'France'),
(7, 'John Miller', 'Pappelallee 21', 'Arnsdorf', '09661', 'Germany'),
(8, 'Rose Joyce', 'Via Galileo Ferraris, 38', 'Malavicina MN', '46040', 'Italy'),
(9, 'Phillip Tilton', 'Huibertplaat 120', 'DH  Zwolle', '8032', 'Netherland'),
(10, 'Anita McGurk', '128 St Pauls Court Cloverlea', 'Palmerston North', '4412', 'New Zealand'),
(11, 'John Morgan', '286 Stanza Bopape St', 'Louis Trichardt', '0923', 'South Africa'),
(12, 'Margaret Teets', 'Grossmatt 62', 'Betschwanden', '8777', 'Switzerland'),
(13, 'Dara Adams', '21 Fraserburgh Rd', 'LINNELS', 'NE46 8YB', 'United Kingdom'),
(14, 'Bennie J. Martin', '34 Masthead Drive', 'PARK AVENUE QLD', '4701', 'Australia'),
(15, 'Gladys Ashford', 'Holzstrasse 14', 'SALCHENDORF', '9064', 'Austria'),
(16, 'William Lavallie', 'Heirstraat 31', 'Marchin', '4570', 'Belgium'),
(17, 'Antonio Wayman', '2331 Carlson Road', 'Prince George', 'BC V2L 5E5', 'Canada'),
(18, 'Carol Selders', 'Ysitie 44', 'TAMPERE', '33240', 'Finland'),
(19, 'David Sato', '30, Rue de la Pompe', 'MANOSQUE', '04100', 'France'),
(20, 'Amy Vanmatre', 'Friedrichstrasse 4', 'Dusseldorf Flehe', '40223', 'Germany'),
(21, 'Kenny Todd', 'Corso Porta Nuova, 10', 'Quara RE', '42010', 'Italy'),
(22, 'Marla Alvarez', 'Tielstraat 17', 'Amsterdam-Zuidoost', '1107 RC', 'Netherland'),
(23, 'George Stanley', '95 Belle Verde Drive Rothesay Bay', 'North Shore', '0630', 'New Zealand'),
(24, 'David Bennett', 'Torvbakkgata 219', 'OSLO', '0550', 'Norway'),
(25, 'Donald Garrett', '86 St Denys Road', 'POYS STREET', 'IP17 9TF', 'United Kingdom'),
(26, 'Horace Morgan', '3435 Jarvis Street', 'Buffalo', '14202', 'United States');


Step 2 - Insert Angular, Angular Datatables, Bootstrap and Jquery File


After this we want to include different library files like AngularJs, AngularJS Datatables plugin, Jquery Datatables plugin, Jquery library and Bootstrap lirary link at header of our index page.


     <head>
  <script src="jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="angular-datatables.min.js"></script>
  <script src="jquery.dataTables.min.js"></script>
  <link rel="stylesheet" href="bootstrap.min.css">
  <link rel="stylesheet" href="datatables.bootstrap.css">
 </head>


Step 3 - Write HTML Code


Now we have to write some HTML code in index.html page. In this code we have define ng-app and ng-controller angular directive which will load module and handle the controller in our AngularJS application.


                   <div ng-app="customerApp" ng-controller="customerController" class="container">

   <br />
   <h3 align="center">How to Use Jquery Datatable with AngularJS & PHP</h3>
   <br />

   <table datatable="ng" dt-options="vm.dtOptions" class="table table-striped table-bordered">
    <thead>
     <tr>
      <th>Sr</th>
      <th>Customer Name</th>
      <th>Address</th>
      <th>City</th>
      <th>Postal Code</th>
      <th>Country</th>
     </tr>
    </thead>
    <tbody>
     <tr ng-repeat="customer in customers">
      <td>{{ $index + 1 }}</td>
      <td>{{ customer.CustomerName }}</td>
      <td>{{ customer.Address }}</td>
      <td>{{ customer.City }}</td>
      <td>{{ customer.PostalCode }}</td>
      <td>{{ customer.Country }}</td>
     </tr>
    </tbody>
   </table>
   <br />
   <br />
  </div>


Step 4 - Write AngularJS code for Fetch Data


After this we have to move to write AngularJS code in which we have load AngularJS datatables module and also handle controller. After this we have send Ajax request to PHP server side script to fetch.php and get customers data from our Mysql database.


<script>

var app = angular.module('customerApp', ['datatables']);

app.controller('customerController', function($scope, $http){
 $http.get('fetch.php').success(function(data, status, headers, config){
  $scope.customers = data;
 });
});

</script>


Step 5 - Fetch Recrods from Mysql Database


Lastly we have to write PHP code in fetch.php file and fetch data from Mysql database table tbl_customer. Here we want to convert data in JSON format for display data on datatables. So for this we have first store data in PHP Array and convert into JSON string by using json_encode() function.


<?php

//fetch.php

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

$query = "SELECT * FROM tbl_customer ORDER BY CustomerID DESC";

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

$statement->execute();

while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
 $data[] = $row;
}

echo json_encode($data);

?>


If you want to see live demo of Jquery Datatables server side processing using AngularJS & PHP, so you have to see demo link below and if you want to download complete source code then also you can find download link below also.






Friday, 20 April 2018

Live search in Laravel using AJAX



In this tutorial, We will learn the process of making a live search in Laravel and AJAX. If we have on a blog or any ecommerce website, a search texbox is always an required feature of Website User Interface. Now a days using of simple search bar is left. Because a live search of data is enough more useful than a plain search bar because it will load data of content in real time without refresh of web page. This will increment the chance of increase a sale because the customer can see the more section of related products.

For demonstrate the functionality of live search, We will make customer table and search box for search live data through all column of customer table and display filter data on web page.



Create the Controller


First we have to make database connection in Laravel application and then after making of database connection we have to create controller in Laravel. For this we have to write following command in your terminal.


php artisan make:controller LiveSearch


Now go tp app/Http/controller/LiveSearch.phpand paste the following code in it.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class LiveSearch extends Controller
{
    function index()
    {
     return view('live_search');
    }

    function action(Request $request)
    {
     if($request->ajax())
     {
      $output = '';
      $query = $request->get('query');
      if($query != '')
      {
       $data = DB::table('tbl_customer')
         ->where('CustomerName', 'like', '%'.$query.'%')
         ->orWhere('Address', 'like', '%'.$query.'%')
         ->orWhere('City', 'like', '%'.$query.'%')
         ->orWhere('PostalCode', 'like', '%'.$query.'%')
         ->orWhere('Country', 'like', '%'.$query.'%')
         ->orderBy('CustomerID', 'desc')
         ->get();
         
      }
      else
      {
       $data = DB::table('tbl_customer')
         ->orderBy('CustomerID', 'desc')
         ->get();
      }
      $total_row = $data->count();
      if($total_row > 0)
      {
       foreach($data as $row)
       {
        $output .= '
        <tr>
         <td>'.$row->CustomerName.'</td>
         <td>'.$row->Address.'</td>
         <td>'.$row->City.'</td>
         <td>'.$row->PostalCode.'</td>
         <td>'.$row->Country.'</td>
        </tr>
        ';
       }
      }
      else
      {
       $output = '
       <tr>
        <td align="center" colspan="5">No Data Found</td>
       </tr>
       ';
      }
      $data = array(
       'table_data'  => $output,
       'total_data'  => $total_row
      );

      echo json_encode($data);
     }
    }
}







Now We have seen code and understand how code is working here. First we have create as index function which load view file we will create in the next step. After this we have we create one more function action that will received variable from search textbox through Ajax request and execute database query for search or filter data. This query will fetch all data from customer database where particular search query will match any table column of customer table data and finally it will converted that filter data into HTML format and return as response.

Create a View

Now here our controller is ready, So We will move to next step for create a view for search bar. For this we have to go to resources/views/live_search.blade.php. NExt we have add the following code into.


<!DOCTYPE html>
<html>
 <head>
  <title>Live search 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">Live search in laravel using AJAX</h3><br />
   <div class="panel panel-default">
    <div class="panel-heading">Search Customer Data</div>
    <div class="panel-body">
     <div class="form-group">
      <input type="text" name="search" id="search" class="form-control" placeholder="Search Customer Data" />
     </div>
     <div class="table-responsive">
      <h3 align="center">Total Data : <span id="total_records"></span></h3>
      <table class="table table-striped table-bordered">
       <thead>
        <tr>
         <th>Customer Name</th>
         <th>Address</th>
         <th>City</th>
         <th>Postal Code</th>
         <th>Country</th>
        </tr>
       </thead>
       <tbody>

       </tbody>
      </table>
     </div>
    </div>    
   </div>
  </div>
 </body>
</html>

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

 fetch_customer_data();

 function fetch_customer_data(query = '')
 {
  $.ajax({
   url:"{{ route('live_search.action') }}",
   method:'GET',
   data:{query:query},
   dataType:'json',
   success:function(data)
   {
    $('tbody').html(data.table_data);
    $('#total_records').text(data.total_data);
   }
  })
 }

 $(document).on('keyup', '#search', function(){
  var query = $(this).val();
  fetch_customer_data(query);
 });
});
</script>


Now we have discuss above code. In body tag we have use Bootstrap panel for display customer data in table format with on search textbox. And in below we can see Jquery code in which we have use Ajax script.

Here Ajax script will pick the value from search textbox as we have type into for search something. It will send value to action method of LiveSearch controller. Under this method it will search data into database according to value of search textbox and get the response back to Ajax request. Once it has received then it will display response of data on web page in HTML table format.

Set the Routes


Lastly we want to set the route for LiveSearch controller two method which we have seen, for this we have to go to routes/web.php and write following code into it.


<?php

Route::get('/live_search', 'LiveSearch@index');
Route::get('/live_search/action', 'LiveSearch@action')->name('live_search.action');

?>


So, here we have discuss how to make live search in Laravel by using Ajax by using simple coding method.

Wednesday, 18 April 2018

Shopping Cart by using Bootstrap Popover with Ajax PHP


In this post, we will see a simple PHP Ajax example for making a shopping cart application using Bootstrap Popover. This PHP Ajax shopping cart application is explicitly kept easy and as less as available. If you want to get this script then You can just download this script and simply customize it as per your requirement. Here, we have load a list of items for shopping cart from the mysql database by using Jquery Ajax. For every item, we can enter item quantity as per our need and simply add into cart by using Ajax with PHP. The cart details will be stored in the PHP session and which we will fetch by using Ajax function call. Here we will display shopping cart details into Bootstrap popover. So we have to just click on anchor tag and Bootstrap popover will be slide down on web page with shopping cart details. In this shopping cart we can remove single product item also and we can also clear whole shopping cart by single click using Ajax, so here ajax will send ajax request to php script and it will clear session item, so whole shopping cart will be empty.



Bootstrap Popover for Shopping Cart


Here we have use Bootstrap popover plugin for display shopping cart details. So first we have to write HTML code for Bootstrap popover. Here we have use Bootstrap nav class for header menu and on this menu we have display Bootstrap popover plugin link. So when we have click on that link then popover will be slide down on web page in which we can see cart details.


<div class="container">
   <br />
   <h3 align="center">PHP Ajax Shopping Cart by using Bootstrap Popover</h3>
   <br />
   <nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
     <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="sr-only">Menu</span>
      <span class="glyphicon glyphicon-menu-hamburger"></span>
      </button>
      <a class="navbar-brand" href="/">Webslesson</a>
     </div>
     
     <div id="navbar-cart" class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
       <li>
        <a id="cart-popover" class="btn" data-placement="bottom" title="Shopping Cart">
         <span class="glyphicon glyphicon-shopping-cart"></span>
         <span class="badge"></span>
         <span class="total_price">$ 0.00</span>
        </a>
       </li>
      </ul>
     </div>
     
    </div>
   </nav>
   <div id="popover_content_wrapper" style="display: none">
    <span id="cart_details"></span>
    <div align="right">
     <a href="#" class="btn btn-primary" id="check_out_cart">
     <span class="glyphicon glyphicon-shopping-cart"></span> Check out
     </a>
     <a href="#" class="btn btn-default" id="clear_cart">
     <span class="glyphicon glyphicon-trash"></span> Clear
     </a>
    </div>
   </div>

   <div id="display_item">


   </div>
   
  </div>


For Activate Bootstrap popover we have write following jquery code, so when we have click on anchor tag with id cart-popover then popover will be slide down on web page with shopping cart details.


$('#cart-popover').popover({
  html : true,
        container: 'body',
        content:function(){
         return $('#popover_content_wrapper').html();
        }
});


Load Item for Shopping Cart


Now we have move to load product on web page for shopping cart by using PHP Ajax. For this we have make one function with Ajax request. This function has been called when page has been load on web browser this function will be called and it will display product on web page under division tag with id display_item.


<!-- index.php !-->

load_product();

function load_product()
{
              $.ajax({
   url:"fetch_item.php",
   method:"POST",
   success:function(data)
   {
    $('#display_item').html(data);
   }
  });
}



<?php

//fetch_item.php

include('database_connection.php');

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

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

if($statement->execute())
{
 $result = $statement->fetchAll();
 $output = '';
 foreach($result as $row)
 {
  $output .= '
  <div class="col-md-3" style="margin-top:12px;">  
            <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
             <img src="images/'.$row["image"].'" class="img-responsive" /><br />
             <h4 class="text-info">'.$row["name"].'</h4>
             <h4 class="text-danger">$ '.$row["price"] .'</h4>
             <input type="text" name="quantity" id="quantity' . $row["id"] .'" class="form-control" value="1" />
             <input type="hidden" name="hidden_name" id="name'.$row["id"].'" value="'.$row["name"].'" />
             <input type="hidden" name="hidden_price" id="price'.$row["id"].'" value="'.$row["price"].'" />
             <input type="button" name="add_to_cart" id="'.$row["id"].'" style="margin-top:5px;" class="btn btn-success form-control add_to_cart" value="Add to Cart" />
            </div>
        </div>
  ';
 }
 echo $output;
}


?>








Fetch Shopping Cart Details


Now we want to make on jquery function which will fetch shopping cart details which we have store in PHP Session. So in this function we have use Ajax request which send request to PHP script and that script will fetch shopping cart details which we have store into Session variable, then that details will be converted into html table format and send back to Ajax request and it will display that cart details under Bootstrap popover by using Jquery. This jquery function will be called when page has been load on browser.


<!-- index.php !-->
<script>  
$(document).ready(function(){

load_cart_data();

function load_cart_data()
{
  $.ajax({
   url:"fetch_cart.php",
   method:"POST",
   dataType:"json",
   success:function(data)
   {
    $('#cart_details').html(data.cart_details);
    $('.total_price').text(data.total_price);
    $('.badge').text(data.total_item);
   }
  });
}
</script>



<?php

//fetch_cart.php

session_start();

$total_price = 0;
$total_item = 0;

$output = '
<div class="table-responsive" id="order_table">
 <table class="table table-bordered table-striped">
  <tr>  
            <th width="40%">Product Name</th>  
            <th width="10%">Quantity</th>  
            <th width="20%">Price</th>  
            <th width="15%">Total</th>  
            <th width="5%">Action</th>  
        </tr>
';
if(!empty($_SESSION["shopping_cart"]))
{
 foreach($_SESSION["shopping_cart"] as $keys => $values)
 {
  $output .= '
  <tr>
   <td>'.$values["product_name"].'</td>
   <td>'.$values["product_quantity"].'</td>
   <td align="right">$ '.$values["product_price"].'</td>
   <td align="right">$ '.number_format($values["product_quantity"] * $values["product_price"], 2).'</td>
   <td><button name="delete" class="btn btn-danger btn-xs delete" id="'. $values["product_id"].'">Remove</button></td>
  </tr>
  ';
  $total_price = $total_price + ($values["product_quantity"] * $values["product_price"]);
  $total_item = $total_item + 1;
 }
 $output .= '
 <tr>  
        <td colspan="3" align="right">Total</td>  
        <td align="right">$ '.number_format($total_price, 2).'</td>  
        <td></td>  
    </tr>
 ';
}
else
{
 $output .= '
    <tr>
     <td colspan="5" align="center">
      Your Cart is Empty!
     </td>
    </tr>
    ';
}
$output .= '</table></div>';
$data = array(
 'cart_details'  => $output,
 'total_price'  => '$' . number_format($total_price, 2),
 'total_item'  => $total_item
); 

echo json_encode($data);


?>


Add Items into Shopping Cart


Now we have completed working on display product on web page that means we have make product catalog on web page and we have also make jquery ajax function for fetch shopping cart details from PHP Session variable display on web page. On product catalog we have put 'Add to Cart' button on each product, so by clicking on that button we can add items into shopping cart by using Ajax with PHP. So, When we have click on the 'Add to cart' button, then we add particular product id and its quantity into a shopping cart. For storing shopping cart details we have use PHP SESSION variable. In Following code you can understand how to add items into shopping cart session variable and if we have add single item multiple times then it's quantity will be increment. Here we have use Ajax request with JQuery PHP for add item into cart.


<!--- index.php ---!>
<script>  
$(document).ready(function(){

 $(document).on('click', '.add_to_cart', function(){
  var product_id = $(this).attr("id");
  var product_name = $('#name'+product_id+'').val();
  var product_price = $('#price'+product_id+'').val();
  var product_quantity = $('#quantity'+product_id).val();
  var action = "add";
  if(product_quantity > 0)
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{product_id:product_id, product_name:product_name, product_price:product_price, product_quantity:product_quantity, action:action},
    success:function(data)
    {
     load_cart_data();
     alert("Item has been Added into Cart");
    }
   });
  }
  else
  {
   alert("lease Enter Number of Quantity");
  }
 });

</script>



<?php

//action.php

session_start();

if(isset($_POST["action"]))
{
 if($_POST["action"] == "add")
 {
  if(isset($_SESSION["shopping_cart"]))
  {
   $is_available = 0;
   foreach($_SESSION["shopping_cart"] as $keys => $values)
   {
    if($_SESSION["shopping_cart"][$keys]['product_id'] == $_POST["product_id"])
    {
     $is_available++;
     $_SESSION["shopping_cart"][$keys]['product_quantity'] = $_SESSION["shopping_cart"][$keys]['product_quantity'] + $_POST["product_quantity"];
    }
   }
   if($is_available == 0)
   {
    $item_array = array(
     'product_id'               =>     $_POST["product_id"],  
     'product_name'             =>     $_POST["product_name"],  
     'product_price'            =>     $_POST["product_price"],  
     'product_quantity'         =>     $_POST["product_quantity"]
    );
    $_SESSION["shopping_cart"][] = $item_array;
   }
  }
  else
  {
   $item_array = array(
    'product_id'               =>     $_POST["product_id"],  
    'product_name'             =>     $_POST["product_name"],  
    'product_price'            =>     $_POST["product_price"],  
    'product_quantity'         =>     $_POST["product_quantity"]
   );
   $_SESSION["shopping_cart"][] = $item_array;
  }
 }
}

?>


Remov Single Item or Clear Cart Details


Here we have make shopping cart in which user can to remove single item from the cart by click on Remove button which can be find on in each row of cart. And We have also allow to user clear all items from cart by click on clear button which user can find under Bootstrap popover shopping cart. When we have click on Remove button, then it will call jquery code and in that we have send Ajax request to PHP script for remove particular item from PHP SESSION variable based on value of product id. For this we have use PHP unset() function for clear single item or all item from cart. In following code you can find how to use Jquery Ajax code for remove single item from cart or remove all items from shopping cart.


<!--- index.php !--->
<script>  
$(document).ready(function(){

 $(document).on('click', '.delete', function(){
  var product_id = $(this).attr("id");
  var action = 'remove';
  if(confirm("Are you sure you want to remove this product?"))
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{product_id:product_id, action:action},
    success:function()
    {
     load_cart_data();
     $('#cart-popover').popover('hide');
     alert("Item has been removed from Cart");
    }
   })
  }
  else
  {
   return false;
  }
 });

 $(document).on('click', '#clear_cart', function(){
  var action = 'empty';
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{action:action},
   success:function()
   {
    load_cart_data();
    $('#cart-popover').popover('hide');
    alert("Your Cart has been clear");
   }
  });
 });
    
});

</script>



<?php

//action.php

session_start();

if(isset($_POST["action"]))
{

 if($_POST["action"] == 'remove')
 {
  foreach($_SESSION["shopping_cart"] as $keys => $values)
  {
   if($values["product_id"] == $_POST["product_id"])
   {
    unset($_SESSION["shopping_cart"][$keys]);
   }
  }
 }
 if($_POST["action"] == 'empty')
 {
  unset($_SESSION["shopping_cart"]);
 }
}

?>


So, this is simple tutorial on How to use Bootstrap Popover plugin for make Shopping cart by using PHP Ajax Jquery with Mysql.




Monday, 16 April 2018

Live Email Availability in Laravel using Ajax



In this tutorial, We will learn implement live email available or not for registration using Ajax Jquery Mysql in Laravel application. This is a most common and very popular feature in most of the web application.

While register a new user account then user enters their email address fields then an Ajax call will request send to Laravel controller for check email availability status of the particular email address which user has enter. In Laravel Controller it will matches the user email against the mysql database and if email already register then it will return email already register and register button will be disabled and if email available for registration then register button will be enabled.





For this first we want to make database connection in going to .env file and config/database.php file. After this we have make one EmailAvailable.php controller by write following command in command prompt.


php artisan make:controller EmailAvailable


Under this controller we have make index() method for load view file on browser. For this we have write following code.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class EmailAvailable extends Controller
{
    function index()
    {
     return view('email_available');
    }

}

?>


In email_available.php we have define email, password and register html field. And Below this we have write jquery code for check email in proper format and also write Ajax request for check email already available or not in our database. It will send Ajax request to check() method of EmailAvailable controller.


<!DOCTYPE html>
<html>
 <head>
  <title>Live Email Availability 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>
  <style type="text/css">
   .box{
    width:600px;
    margin:0 auto;
    border:1px solid #ccc;
   }
   .has-error
   {
    border-color:#cc0000;
    background-color:#ffff99;
   }
  </style>
 </head>
 <body>
  <br />
  <div class="container box">
   <h3 align="center">Live Email Availability in Laravel using Ajax</h3><br />
   
   <div class="form-group">
    <label>Enter Your Email</label>
    <input type="text" name="email" id="email" class="form-control input-lg" />
    <span id="error_email"></span>
   </div>
   <div class="form-group">
    <label>Enter Your Password</label>
    <input type="password" name="password" id="password" class="form-control input-lg" />
   </div>
   <div class="form-group" align="center">
    <button type="button" name="register" id="register" class="btn btn-info btn-lg">Register</button>
   </div>
   {{ csrf_field() }}
   
   <br />
   <br />
  </div>
 </body>
</html>

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

 $('#email').blur(function(){
  var error_email = '';
  var email = $('#email').val();
  var _token = $('input[name="_token"]').val();
  var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  if(!filter.test(email))
  {    
   $('#error_email').html('<label class="text-danger">Invalid Email</label>');
   $('#email').addClass('has-error');
   $('#register').attr('disabled', 'disabled');
  }
  else
  {
   $.ajax({
    url:"{{ route('email_available.check') }}",
    method:"POST",
    data:{email:email, _token:_token},
    success:function(result)
    {
     if(result == 'unique')
     {
      $('#error_email').html('<label class="text-success">Email Available</label>');
      $('#email').removeClass('has-error');
      $('#register').attr('disabled', false);
     }
     else
     {
      $('#error_email').html('<label class="text-danger">Email not Available</label>');
      $('#email').addClass('has-error');
      $('#register').attr('disabled', 'disabled');
     }
    }
   })
  }
 });
 
});
</script>


For received Ajax request we have go EmailAvailable.php controller and under this we have create check method. This method will check particular email is available or not in mysql database. For this we have use Laravel DB class.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class EmailAvailable extends Controller
{
    function index()
    {
     return view('email_available');
    }

    function check(Request $request)
    {
     if($request->get('email'))
     {
      $email = $request->get('email');
      $data = DB::table("tbl_login")
       ->where('email', $email)
       ->count();
      if($data > 0)
      {
       echo 'not_unique';
      }
      else
      {
       echo 'unique';
      }
     }
    }

}
?>


Lastly we want to set route for both method of EmailAvailable controller. For this we have to go to routes/web.php file.


<?php


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

Route::get('/email_available', 'EmailAvailable@index');

Route::post('/email_available/check', 'EmailAvailable@check')->name('email_available.check');





Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_login`
--

CREATE TABLE `tbl_login` (
  `id` int(11) NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `gender` varchar(30) NOT NULL,
  `email` varchar(200) NOT NULL,
  `password` varchar(200) NOT NULL,
  `address` text NOT NULL,
  `mobile_no` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_login`
--
ALTER TABLE `tbl_login`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;





Saturday, 14 April 2018

Multi Step Responsive Form Using JQuery Bootstrap PHP


We have to required many details from users at the time of registration. For capture lots of information at the time of registration we have to make long registration form on our website. So reduce headache of long registration form we have divide that form information in smaller logical section and convert into multi step registration form. This type of multi step form will improve usability of our website as compare to long form. This multi step form we have not only use in registration but we can also in any event where we want to insert lots of data. For making multi step form we have use Bootstrap library and Jquery with PHP server script.

In current scenario web development multistep forms are more popular that long form due to more user user friendliness. Multi step form give us easy step by step fill to complete long procedure form. If there are in long form with too many HTML input fields for fill details then we can break that many input fields into different multiple smaller forms fields, forms filling to user to make it more convenient. And In Multi step form we can divide form validation into different step, so if previous form validation run properly then user can go to next step. So in multi step form can divide validation into different step.

So in this post we have discuss how to make Multi Step Form by using Bootstrap JQuery with PHP PDO and Mysql. By using we will make multi step form which will provide useful functionality to user then input too much data into form. So, We will divide form input fields data into steps and if user has fill first step with proper validation then he can go to next step clicking on next button only and suppose user want to go previous step then he can only go previous step by clicking on previous button only. When use has complete to fill data in all step will proper form validation and he has come to final step then on final step user can submit form data to server. So, multi step form method will reduce human error while filling of data because each step data has varify on that step and if data properly filled then he can go to next step. So, here we have make multi step form by using Jquery Bootstrap with PHP PDO and Mysql.







Source Code


index.php



<?php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
$message = '';
if(isset($_POST["email"]))
{
 sleep(5);
 $query = "
 INSERT INTO tbl_login 
 (first_name, last_name, gender, email, password, address, mobile_no) VALUES 
 (:first_name, :last_name, :gender, :email, :password, :address, :mobile_no)
 ";
 $password_hash = password_hash($_POST["password"], PASSWORD_DEFAULT);
 $user_data = array(
  ':first_name'  => $_POST["first_name"],
  ':last_name'  => $_POST["last_name"],
  ':gender'   => $_POST["gender"],
  ':email'   => $_POST["email"],
  ':password'   => $password_hash,
  ':address'   => $_POST["address"],
  ':mobile_no'  => $_POST["mobile_no"]
 );
 $statement = $connect->prepare($query);
 if($statement->execute($user_data))
 {
  $message = '
  <div class="alert alert-success">
  Registration Completed Successfully
  </div>
  ';
 }
 else
 {
  $message = '
  <div class="alert alert-success">
  There is an error in Registration
  </div>
  ';
 }
}
?>

<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Multi Step Registration Form Using JQuery Bootstrap in PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
  <style>
  .box
  {
   width:800px;
   margin:0 auto;
  }
  .active_tab1
  {
   background-color:#fff;
   color:#333;
   font-weight: 600;
  }
  .inactive_tab1
  {
   background-color: #f5f5f5;
   color: #333;
   cursor: not-allowed;
  }
  .has-error
  {
   border-color:#cc0000;
   background-color:#ffff99;
  }
  </style>
 </head>
 <body>
 <br />
  <div class="container box">
   <br />
   <h2 align="center">Multi Step Registration Form Using JQuery Bootstrap in PHP</h2><br />
   <?php echo $message; ?>
   <form method="post" id="register_form">
    <ul class="nav nav-tabs">
     <li class="nav-item">
      <a class="nav-link active_tab1" style="border:1px solid #ccc" id="list_login_details">Login Details</a>
     </li>
     <li class="nav-item">
      <a class="nav-link inactive_tab1" id="list_personal_details" style="border:1px solid #ccc">Personal Details</a>
     </li>
     <li class="nav-item">
      <a class="nav-link inactive_tab1" id="list_contact_details" style="border:1px solid #ccc">Contact Details</a>
     </li>
    </ul>
    <div class="tab-content" style="margin-top:16px;">
     <div class="tab-pane active" id="login_details">
      <div class="panel panel-default">
       <div class="panel-heading">Login Details</div>
       <div class="panel-body">
        <div class="form-group">
         <label>Enter Email Address</label>
         <input type="text" name="email" id="email" class="form-control" />
         <span id="error_email" class="text-danger"></span>
        </div>
        <div class="form-group">
         <label>Enter Password</label>
         <input type="password" name="password" id="password" class="form-control" />
         <span id="error_password" class="text-danger"></span>
        </div>
        <br />
        <div align="center">
         <button type="button" name="btn_login_details" id="btn_login_details" class="btn btn-info btn-lg">Next</button>
        </div>
        <br />
       </div>
      </div>
     </div>
     <div class="tab-pane fade" id="personal_details">
      <div class="panel panel-default">
       <div class="panel-heading">Fill Personal Details</div>
       <div class="panel-body">
        <div class="form-group">
         <label>Enter First Name</label>
         <input type="text" name="first_name" id="first_name" class="form-control" />
         <span id="error_first_name" class="text-danger"></span>
        </div>
        <div class="form-group">
         <label>Enter Last Name</label>
         <input type="text" name="last_name" id="last_name" class="form-control" />
         <span id="error_last_name" class="text-danger"></span>
        </div>
        <div class="form-group">
         <label>Gender</label>
         <label class="radio-inline">
          <input type="radio" name="gender" value="male" checked> Male
         </label>
         <label class="radio-inline">
          <input type="radio" name="gender" value="female"> Female
         </label>
        </div>
        <br />
        <div align="center">
         <button type="button" name="previous_btn_personal_details" id="previous_btn_personal_details" class="btn btn-default btn-lg">Previous</button>
         <button type="button" name="btn_personal_details" id="btn_personal_details" class="btn btn-info btn-lg">Next</button>
        </div>
        <br />
       </div>
      </div>
     </div>
     <div class="tab-pane fade" id="contact_details">
      <div class="panel panel-default">
       <div class="panel-heading">Fill Contact Details</div>
       <div class="panel-body">
        <div class="form-group">
         <label>Enter Address</label>
         <textarea name="address" id="address" class="form-control"></textarea>
         <span id="error_address" class="text-danger"></span>
        </div>
        <div class="form-group">
         <label>Enter Mobile No.</label>
         <input type="text" name="mobile_no" id="mobile_no" class="form-control" />
         <span id="error_mobile_no" class="text-danger"></span>
        </div>
        <br />
        <div align="center">
         <button type="button" name="previous_btn_contact_details" id="previous_btn_contact_details" class="btn btn-default btn-lg">Previous</button>
         <button type="button" name="btn_contact_details" id="btn_contact_details" class="btn btn-success btn-lg">Register</button>
        </div>
        <br />
       </div>
      </div>
     </div>
    </div>
   </form>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 $('#btn_login_details').click(function(){
  
  var error_email = '';
  var error_password = '';
  var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  
  if($.trim($('#email').val()).length == 0)
  {
   error_email = 'Email is required';
   $('#error_email').text(error_email);
   $('#email').addClass('has-error');
  }
  else
  {
   if (!filter.test($('#email').val()))
   {
    error_email = 'Invalid Email';
    $('#error_email').text(error_email);
    $('#email').addClass('has-error');
   }
   else
   {
    error_email = '';
    $('#error_email').text(error_email);
    $('#email').removeClass('has-error');
   }
  }
  
  if($.trim($('#password').val()).length == 0)
  {
   error_password = 'Password is required';
   $('#error_password').text(error_password);
   $('#password').addClass('has-error');
  }
  else
  {
   error_password = '';
   $('#error_password').text(error_password);
   $('#password').removeClass('has-error');
  }

  if(error_email != '' || error_password != '')
  {
   return false;
  }
  else
  {
   $('#list_login_details').removeClass('active active_tab1');
   $('#list_login_details').removeAttr('href data-toggle');
   $('#login_details').removeClass('active');
   $('#list_login_details').addClass('inactive_tab1');
   $('#list_personal_details').removeClass('inactive_tab1');
   $('#list_personal_details').addClass('active_tab1 active');
   $('#list_personal_details').attr('href', '#personal_details');
   $('#list_personal_details').attr('data-toggle', 'tab');
   $('#personal_details').addClass('active in');
  }
 });
 
 $('#previous_btn_personal_details').click(function(){
  $('#list_personal_details').removeClass('active active_tab1');
  $('#list_personal_details').removeAttr('href data-toggle');
  $('#personal_details').removeClass('active in');
  $('#list_personal_details').addClass('inactive_tab1');
  $('#list_login_details').removeClass('inactive_tab1');
  $('#list_login_details').addClass('active_tab1 active');
  $('#list_login_details').attr('href', '#login_details');
  $('#list_login_details').attr('data-toggle', 'tab');
  $('#login_details').addClass('active in');
 });
 
 $('#btn_personal_details').click(function(){
  var error_first_name = '';
  var error_last_name = '';
  
  if($.trim($('#first_name').val()).length == 0)
  {
   error_first_name = 'First Name is required';
   $('#error_first_name').text(error_first_name);
   $('#first_name').addClass('has-error');
  }
  else
  {
   error_first_name = '';
   $('#error_first_name').text(error_first_name);
   $('#first_name').removeClass('has-error');
  }
  
  if($.trim($('#last_name').val()).length == 0)
  {
   error_last_name = 'Last Name is required';
   $('#error_last_name').text(error_last_name);
   $('#last_name').addClass('has-error');
  }
  else
  {
   error_last_name = '';
   $('#error_last_name').text(error_last_name);
   $('#last_name').removeClass('has-error');
  }

  if(error_first_name != '' || error_last_name != '')
  {
   return false;
  }
  else
  {
   $('#list_personal_details').removeClass('active active_tab1');
   $('#list_personal_details').removeAttr('href data-toggle');
   $('#personal_details').removeClass('active');
   $('#list_personal_details').addClass('inactive_tab1');
   $('#list_contact_details').removeClass('inactive_tab1');
   $('#list_contact_details').addClass('active_tab1 active');
   $('#list_contact_details').attr('href', '#contact_details');
   $('#list_contact_details').attr('data-toggle', 'tab');
   $('#contact_details').addClass('active in');
  }
 });
 
 $('#previous_btn_contact_details').click(function(){
  $('#list_contact_details').removeClass('active active_tab1');
  $('#list_contact_details').removeAttr('href data-toggle');
  $('#contact_details').removeClass('active in');
  $('#list_contact_details').addClass('inactive_tab1');
  $('#list_personal_details').removeClass('inactive_tab1');
  $('#list_personal_details').addClass('active_tab1 active');
  $('#list_personal_details').attr('href', '#personal_details');
  $('#list_personal_details').attr('data-toggle', 'tab');
  $('#personal_details').addClass('active in');
 });
 
 $('#btn_contact_details').click(function(){
  var error_address = '';
  var error_mobile_no = '';
  var mobile_validation = /^\d{10}$/;
  if($.trim($('#address').val()).length == 0)
  {
   error_address = 'Address is required';
   $('#error_address').text(error_address);
   $('#address').addClass('has-error');
  }
  else
  {
   error_address = '';
   $('#error_address').text(error_address);
   $('#address').removeClass('has-error');
  }
  
  if($.trim($('#mobile_no').val()).length == 0)
  {
   error_mobile_no = 'Mobile Number is required';
   $('#error_mobile_no').text(error_mobile_no);
   $('#mobile_no').addClass('has-error');
  }
  else
  {
   if (!mobile_validation.test($('#mobile_no').val()))
   {
    error_mobile_no = 'Invalid Mobile Number';
    $('#error_mobile_no').text(error_mobile_no);
    $('#mobile_no').addClass('has-error');
   }
   else
   {
    error_mobile_no = '';
    $('#error_mobile_no').text(error_mobile_no);
    $('#mobile_no').removeClass('has-error');
   }
  }
  if(error_address != '' || error_mobile_no != '')
  {
   return false;
  }
  else
  {
   $('#btn_contact_details').attr("disabled", "disabled");
   $(document).css('cursor', 'prgress');
   $("#register_form").submit();
  }
  
 });
 
});
</script>


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_login`
--

CREATE TABLE `tbl_login` (
  `id` int(11) NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `gender` varchar(30) NOT NULL,
  `email` varchar(200) NOT NULL,
  `password` varchar(200) NOT NULL,
  `address` text NOT NULL,
  `mobile_no` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_login`
--
ALTER TABLE `tbl_login`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;

Tuesday, 10 April 2018

PHP - Sending Multiple Forms Data using JQuery Ajax



In this post we will learn how to send multiple forms data with jQuery and JavaScript code by Ajax with PHP. In simple terms in PHP Ajax JQuery Web Development how can we insert multiple forms data into Mysql database table by using PHP script with Jquery and Ajax. We all know HTML Forms are mainly use on most of the websites for gathering data from a particular user. Alike, forms in this website has been used different method for submit data to server. We have mainly used Simple HTML methods for obtained data from user.

In Such cases in your web development you want to required to insert multiple data in your single form submission. At that time if you have follow simple HTML form submission with PHP script then you are able to send only single data to server. For Sending or inserting or saving multiple data in single click then you have to use Jquery and javascript code. By using Jquery or Javascript code you can generate dynamic HTML field in your HTML form. We can generate any dynamic HTML field by using Jquery and append into your form fields. We can dynamically generate same name HTML field by using Javascript and append into our HTML form.

Here in this case also we have use Jquery and Jquery UI. By using Jquery UI Dialog box we have get data from user and by using Jquery code we have converted that form data into HTML table and data has been stored in hidden field in array format. Here we can add multiple number of data and store into HTML table format. Now for submit multiple form data to PHP server script we have use Ajax web development request. By using Ajax we have send multiple form data to PHP script and in PHP we have insert multiple form data. So, Here we have insert multiple form data in single click of form submission. This is new challenge in Web Development with JQuery Ajax PHP. So, if you have developed any web application development and in that you want to add multiple data in single form submission then you can get reference from this PHP JQuery Ajax Web Development Code.







Source Code


index.php



<!--
//index.php
!-->

<html>  
    <head>  
        <title>PHP - Sending multiple forms data through jQuery Ajax</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="bootstrap.min.css" />
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">PHP - Sending multiple forms data through jQuery Ajax</a></h3><br />
   <br />
   <br />
   <div align="right" style="margin-bottom:5px;">
    <button type="button" name="add" id="add" class="btn btn-success btn-xs">Add</button>
   </div>
   <br />
   <form method="post" id="user_form">
    <div class="table-responsive">
     <table class="table table-striped table-bordered" id="user_data">
      <tr>
       <th>First Name</th>
       <th>Last Name</th>
       <th>Details</th>
       <th>Remove</th>
      </tr>
     </table>
    </div>
    <div align="center">
     <input type="submit" name="insert" id="insert" class="btn btn-primary" value="Insert" />
    </div>
   </form>

   <br />
  </div>
  <div id="user_dialog" title="Add Data">
   <div class="form-group">
    <label>Enter First Name</label>
    <input type="text" name="first_name" id="first_name" class="form-control" />
    <span id="error_first_name" class="text-danger"></span>
   </div>
   <div class="form-group">
    <label>Enter Last Name</label>
    <input type="text" name="last_name" id="last_name" class="form-control" />
    <span id="error_last_name" class="text-danger"></span>
   </div>
   <div class="form-group" align="center">
    <input type="hidden" name="row_id" id="hidden_row_id" />
    <button type="button" name="save" id="save" class="btn btn-info">Save</button>
   </div>
  </div>
  <div id="action_alert" title="Action">

  </div>
    </body>  
</html> 

<script>  
$(document).ready(function(){ 
 
 var count = 0;

 $('#user_dialog').dialog({
  autoOpen:false,
  width:400
 });

 $('#add').click(function(){
  $('#user_dialog').dialog('option', 'title', 'Add Data');
  $('#first_name').val('');
  $('#last_name').val('');
  $('#error_first_name').text('');
  $('#error_last_name').text('');
  $('#first_name').css('border-color', '');
  $('#last_name').css('border-color', '');
  $('#save').text('Save');
  $('#user_dialog').dialog('open');
 });

 $('#save').click(function(){
  var error_first_name = '';
  var error_last_name = '';
  var first_name = '';
  var last_name = '';
  if($('#first_name').val() == '')
  {
   error_first_name = 'First Name is required';
   $('#error_first_name').text(error_first_name);
   $('#first_name').css('border-color', '#cc0000');
   first_name = '';
  }
  else
  {
   error_first_name = '';
   $('#error_first_name').text(error_first_name);
   $('#first_name').css('border-color', '');
   first_name = $('#first_name').val();
  } 
  if($('#last_name').val() == '')
  {
   error_last_name = 'Last Name is required';
   $('#error_last_name').text(error_last_name);
   $('#last_name').css('border-color', '#cc0000');
   last_name = '';
  }
  else
  {
   error_last_name = '';
   $('#error_last_name').text(error_last_name);
   $('#last_name').css('border-color', '');
   last_name = $('#last_name').val();
  }
  if(error_first_name != '' || error_last_name != '')
  {
   return false;
  }
  else
  {
   if($('#save').text() == 'Save')
   {
    count = count + 1;
    output = '<tr id="row_'+count+'">';
    output += '<td>'+first_name+' <input type="hidden" name="hidden_first_name[]" id="first_name'+count+'" class="first_name" value="'+first_name+'" /></td>';
    output += '<td>'+last_name+' <input type="hidden" name="hidden_last_name[]" id="last_name'+count+'" value="'+last_name+'" /></td>';
    output += '<td><button type="button" name="view_details" class="btn btn-warning btn-xs view_details" id="'+count+'">View</button></td>';
    output += '<td><button type="button" name="remove_details" class="btn btn-danger btn-xs remove_details" id="'+count+'">Remove</button></td>';
    output += '</tr>';
    $('#user_data').append(output);
   }
   else
   {
    var row_id = $('#hidden_row_id').val();
    output = '<td>'+first_name+' <input type="hidden" name="hidden_first_name[]" id="first_name'+row_id+'" class="first_name" value="'+first_name+'" /></td>';
    output += '<td>'+last_name+' <input type="hidden" name="hidden_last_name[]" id="last_name'+row_id+'" value="'+last_name+'" /></td>';
    output += '<td><button type="button" name="view_details" class="btn btn-warning btn-xs view_details" id="'+row_id+'">View</button></td>';
    output += '<td><button type="button" name="remove_details" class="btn btn-danger btn-xs remove_details" id="'+row_id+'">Remove</button></td>';
    $('#row_'+row_id+'').html(output);
   }

   $('#user_dialog').dialog('close');
  }
 });

 $(document).on('click', '.view_details', function(){
  var row_id = $(this).attr("id");
  var first_name = $('#first_name'+row_id+'').val();
  var last_name = $('#last_name'+row_id+'').val();
  $('#first_name').val(first_name);
  $('#last_name').val(last_name);
  $('#save').text('Edit');
  $('#hidden_row_id').val(row_id);
  $('#user_dialog').dialog('option', 'title', 'Edit Data');
  $('#user_dialog').dialog('open');
 });

 $(document).on('click', '.remove_details', function(){
  var row_id = $(this).attr("id");
  if(confirm("Are you sure you want to remove this row data?"))
  {
   $('#row_'+row_id+'').remove();
  }
  else
  {
   return false;
  }
 });

 $('#action_alert').dialog({
  autoOpen:false
 });

 $('#user_form').on('submit', function(event){
  event.preventDefault();
  var count_data = 0;
  $('.first_name').each(function(){
   count_data = count_data + 1;
  });
  if(count_data > 0)
  {
   var form_data = $(this).serialize();
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     $('#user_data').find("tr:gt(0)").remove();
     $('#action_alert').html('<p>Data Inserted Successfully</p>');
     $('#action_alert').dialog('open');
    }
   })
  }
  else
  {
   $('#action_alert').html('<p>Please Add atleast one data</p>');
   $('#action_alert').dialog('open');
  }
 });
 
});  
</script>


insert.php



<?php

//insert.php

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

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

for($count = 0; $count<count($_POST['hidden_first_name']); $count++)
{
 $data = array(
  ':first_name' => $_POST['hidden_first_name'][$count],
  ':last_name' => $_POST['hidden_last_name'][$count]
 );
 $statement = $connect->prepare($query);
 $statement->execute($data);
}

?>