Friday, 15 June 2018

Laravel - How to Generate Dynamic PDF from HTML using DomPDF

Making of Dynamic PDF is required feature of any commercial web application, so here we have publish this post in which we have describe how to create dynamic pdf file in Laravel by using DomPDF library. Suppose we have working on any enterprise level web application by using Laravel then at that time we want to required to make output of our application in PDF report format from dynamic Mysql database. From this post we have make simple tutorial in which we have describe how to can we generate dynamic PDF file in step by step process which better understading to beginner laravel programmer.

In this tutorial we have use laravel-dompdf package for generate dynamic pdf file and by using this package we can also download pdf file in our local computer also. Here we have use mysql customer table, in which we have already inserted some data for create dynamic pdf file from that data in tabular format. For display data in proper in table in pdf file we have also add some inline css in html table code, because we have make pdf file from html by using dompdf package in Laravel.







Step 1 - Download Laravel Dompdf Package


For create PDF file in Laravel first we want to download laravel-dompdf package. For this first we want to write following command in command prompt terminal.


composer require barryvdh/laravel-dompdf


Download this packege we have to register this package into Laravel working environment, for this we have to open config/app.php file and add service provider and aliase details.


'providers' => [
        ..........
        Barryvdh\DomPDF\ServiceProvider::class,
    ],

    'aliases' => [
        ..........
        'PDF' => Barryvdh\DomPDF\Facade::class,
    ],


Step 2 - Create Controller


After this we have to create controller in our Laravel application by using composer command. This controller will handle http requrest to convert html code to PDF file.


php artisan make:controller DynamicPDFController


This command will make controller in app/Http/Controllers folder with name like DynamicPDFController.php. In this controller first we have to make index() method for fetch data from database and here for fetch data we have to get_customer_data() method and after this in index() method we have send data to view file. For convert HTML data to PDF we have make another method pdf() by using this method it will convert html code to PDF file. For html data here we have use convert_customer_data_to_html() method. Below you can find complete controller source code below.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use PDF;

class DynamicPDFController extends Controller
{
    function index()
    {
     $customer_data = $this->get_customer_data();
     return view('dynamic_pdf')->with('customer_data', $customer_data);
    }

    function get_customer_data()
    {
     $customer_data = DB::table('tbl_customer')
         ->limit(10)
         ->get();
     return $customer_data;
    }

    function pdf()
    {
     $pdf = \App::make('dompdf.wrapper');
     $pdf->loadHTML($this->convert_customer_data_to_html());
     return $pdf->stream();
    }

    function convert_customer_data_to_html()
    {
     $customer_data = $this->get_customer_data();
     $output = '
     <h3 align="center">Customer Data</h3>
     <table width="100%" style="border-collapse: collapse; border: 0px;">
      <tr>
    <th style="border: 1px solid; padding:12px;" width="20%">Name</th>
    <th style="border: 1px solid; padding:12px;" width="30%">Address</th>
    <th style="border: 1px solid; padding:12px;" width="15%">City</th>
    <th style="border: 1px solid; padding:12px;" width="15%">Postal Code</th>
    <th style="border: 1px solid; padding:12px;" width="20%">Country</th>
   </tr>
     ';  
     foreach($customer_data as $customer)
     {
      $output .= '
      <tr>
       <td style="border: 1px solid; padding:12px;">'.$customer->CustomerName.'</td>
       <td style="border: 1px solid; padding:12px;">'.$customer->Address.'</td>
       <td style="border: 1px solid; padding:12px;">'.$customer->City.'</td>
       <td style="border: 1px solid; padding:12px;">'.$customer->PostalCode.'</td>
       <td style="border: 1px solid; padding:12px;">'.$customer->Country.'</td>
      </tr>
      ';
     }
     $output .= '</table>';
     return $output;
    }
}


Step 3 - Create view file


After this we have make view file in resources/view/dynamic_pdf.blade.php. This file has received data from controller index() method and display dynamic data in html table format. After this we have make on button for convert this html data to pdf file. When we have click on this button then it has send request to pdf() method of controller which will convert html to PDF file by using dompdf package in laravel which we can see on web page.


<!DOCTYPE html>
<html>
 <head>
  <title>Laravel - How to Generate Dynamic PDF from HTML using DomPDF</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;
   }
  </style>
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Laravel - How to Generate Dynamic PDF from HTML using DomPDF</h3><br />
   
   <div class="row">
    <div class="col-md-7" align="right">
     <h4>Customer Data</h4>
    </div>
    <div class="col-md-5" align="right">
     <a href="{{ url('dynamic_pdf/pdf') }}" class="btn btn-danger">Convert into PDF</a>
    </div>
   </div>
   <br />
   <div class="table-responsive">
    <table class="table table-striped table-bordered">
     <thead>
      <tr>
       <th>Name</th>
       <th>Address</th>
       <th>City</th>
       <th>Postal Code</th>
       <th>Country</th>
      </tr>
     </thead>
     <tbody>
     @foreach($customer_data as $customer)
      <tr>
       <td>{{ $customer->CustomerName }}</td>
       <td>{{ $customer->Address }}</td>
       <td>{{ $customer->City }}</td>
       <td>{{ $customer->PostalCode }}</td>
       <td>{{ $customer->Country }}</td>
      </tr>
     @endforeach
     </tbody>
    </table>
   </div>
  </div>
 </body>
</html>


Step 4 - Add Route


This is last step for generate dynamic pdf file in laravel by using dompdf package and here we want to set route for index() and pdf() method of DynamicPDFController.php file. For this we have to go to app/Http/routes.php and write following code for set route in our laravel application.


Route::get('/dynamic_pdf', 'DynamicPDFController@index');

Route::get('/dynamic_pdf/pdf', 'DynamicPDFController@pdf');


So, this is complete step by step process for create PDF file in Laravel by using Dompdf package.

Monday, 11 June 2018

Auto Refresh Div Content using AngularJS in PHP


In this post we will learn How can we auto refresh any Div tag dynamic content or data by using AngularJS with PHP Script. Because refreshing content of any particular html element of web application page is one of the required functionality in Dynamic web development. For this JavaScript has provide us to use setInterval() method for execute the same task on regular interval with specified time. But we want to do this things in AngularJS, so AngularJS has the wrapper of setInterval() in $Interval angular service module. By using this angular service module we can repeat the same task on regular interval of time.

So, here for refresh a DIV or any element content or data in specified time, we have use $interval service. This Angular service has done same task which we have done by using setInterval() method of javascript but $interval has give us more control like promis callback which can be cancel or stop execute of refresh of data.

For learn how can we use $interval service for Auto refresh of Div content without refresh of web page. So, here we have use PHP script and make simple Chat application by using AngularJS with PHP. In this chat application we have load chat data in Div tag by using AngularJS function which call PHP script for fetch data from Mysql data and display under Div tag. Now we want to auto refresh this Div chat data on every 5 seconds, for this here we have use $interval service of Angular. This service we can use same as setInterval(), in this service also we have put our fetchData() function and set time interval of 5 seconds, so on every 5 second $interval service has called fetchData() function which send request to PHP script for fetch data from Mysql chat table and then after it will display under Div without refresh of webpage. If want to make robust web application by using AngularJS with PHP then this source code will helpful. So, this way it will auto refresh div content by using AngularJS $interval service with PHP.









Source Code



--
-- Database: `testing`
--

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

--
-- Table structure for table `chat`
--

CREATE TABLE `chat` (
  `chat_id` int(11) NOT NULL,
  `chat_content` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `chat`
--
ALTER TABLE `chat`
  ADD PRIMARY KEY (`chat_id`);

--
-- AUTO_INCREMENT for dumped tables
--

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


database_connection.php



<?php

//database_connection.php

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



?>


index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Auto Refresh Div Content using AngularJS in PHP</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <style>
  #load_tweets
    {
      padding:16px;
      background-color:#f1f1f1;
      margin-bottom:30px;
    }
    #load_tweets li
    {
      padding:12px;
      border-bottom:1px dotted #ccc;
      list-style: none;
    }
  </style>
 </head>
 <body>
  <br />
   <h3 align="center">Auto Refresh Div Content using AngularJS in PHP</h3>
  <br />
  <div ng-app="autoRefreshApp" ng-controller="autoRefreshController" class="container" style="width:100%; max-width:600px;">
   <h3 align="center">Chat Page</h3>

   <div class="alert alert-success alert-dismissible" ng-show="success">
    <a href="#" class="close" aria-label="close">&times;</a>
    {{ successMessage }}
   </div>

   <form method="post" ng-model="form_data" ng-submit="submitForm()">
    <div class="form-group">
     <label>Enter Your Message</label>
     <textarea name="content" class="form-control" ng-model="form_data.content"></textarea>
    </div>
    <div class="form-group" align="right">
     <input type="submit" name="submit" class="btn btn-info" value="Send" />
    </div>
   </form>
   <div id="load_tweets">
    <ul>
     <li ng-repeat="messageData in messagesData">
      {{ messageData.chat_content }}
     </li>
    </ul>
   </div>
  </div>
 </body>
</html>

<script>

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

app.controller('autoRefreshController', function($scope, $http, $interval){

 $scope.success = false;

 $scope.submitForm = function(){
  $http({
   method:"POST",
   url:'insert.php', 
   data:$scope.form_data
  }).success(function(data){
   if(data.message != '')
   {
    $scope.form_data = null;
    $scope.success = true;
    $scope.successMessage = data.message;
    $interval(function(){
     $scope.success = false;
    }, 5000);
   }
  });
 };

 $scope.fetchData = function(){
  $http.get('fetch_data.php').success(function(data){
   $scope.messagesData = data;
  });
 };

 $interval(function(){
  $scope.fetchData();
 }, 5000);

});



</script>


insert.php



<?php

//insert.php

include("database_connection.php");

$form_data = json_decode(file_get_contents("php://input"));

if(!empty($form_data->content))
{
 $data = array(
  ':chat_content'  => $form_data->content
 );
 $query = "
 INSERT INTO chat 
 (chat_content) VALUES (:chat_content)
 ";
 $statement = $connect->prepare($query);
 if($statement->execute($data))
 {
  $output = array(
   'message' => 'Message Sended'
  );
  echo json_encode($output);
 }
}

?>


fetch_data.php



<?php

//fetch_data.php

include("database_connection.php");

$query = "SELECT * FROM chat ORDER BY chat_id DESC";

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

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

?>

Saturday, 9 June 2018

How to Take Website Screen Shot From URL in PHP



Capturing of Screenshot of Web page is a one type of functionality which can be used for different purposed in our web application. If you want to put this feature in your web application then there are number of third party APIs are available on the web for capture screenshot of the website from URL. But if you want to make your own script which can take a screenshot of website from URL, then you can get this feature by using PHP with Google PageSpeed Insights API.

Mainly, This Google PageSpeed Insights API is used for calculate the speed of a web page, but we can also use this Google PageSpeed Insights API for capture a website screenshot from URL. In this post we will seen you how can we take a screen shot from URL of website by using Google PageSpeed Insights API with PHP script.

Take Screenshot of Website from URL


To take screenshot of Web page, Google PageSpeed Insights API required to pass following parameters.

  • url - In this parameters we have to pass URL of the website.
  • screenshot - This parameters screenshot=true is used for fetch screenshot data.

Below script you can see how to make a form for take website screenshot from URL which has be entered by use and after this it will load webpage screenshot on page.









Source Code - index.php



<?php

//index.php

$screen_shot_image = '';

if(isset($_POST["screen_shot"]))
{
 $url = $_POST["url"];
 $screen_shot_json_data = file_get_contents("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=$url&screenshot=true");
 $screen_shot_result = json_decode($screen_shot_json_data, true);
 $screen_shot = $screen_shot_result['screenshot']['data'];
 $screen_shot = str_replace(array('_','-'), array('/', '+'), $screen_shot);
 $screen_shot_image = "<img src=\"data:image/jpeg;base64,".$screen_shot."\" class='img-responsive img-thumbnail'/>";
}

?>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>How to capture website screen shot from url 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:100%;
   max-width:720px;
   margin:0 auto;
  }
  </style>
 </head>
 <body>
  <div class="container box">
   <br />
   <h2 align="center">How to capture website screen shot from url in php</h2><br />
   <form method="post">
    <div class="form-group">
     <label>Enter URL</label>
     <input type="url" name="url" class="form-control input-lg" required autocomplete="off" />
    </div>
    <br />
    <br />
    <input type="submit" name="screen_shot" value="Take a Screenshot" class="btn btn-info btn-lg" />
   </form>
   <br />
   <?php
   
   echo $screen_shot_image;
   
   ?>
  </div>
  <div style="clear:both"></div>
  <br />
  
  <br />
  <br />
  <br />
 </body>
</html>

Friday, 8 June 2018

9 Questions to Ask Before Buying a Used or Reconditioned Phone


There are numerous assortments of mobile phones available in the market with different attributes to meet the needs of every mobile user. Most of us may be intent to buy a smartphone that has been released recently. However, for most of us, these expensively priced cell phones are beyond the limit that our pocket can permit. There is no need to get upset and choose some standard phones. There is a way to get a hold of a smart one at a reasonable price. You can buy a reconditioned or used mobile phone that will hardly cost you the one third or half price of its brand new counterpart.

Though getting a used or refurbished mobile phone can save you a lot, you should keep in mind that it can be a daunting task to find out a good deal- good-conditioned phone at an affordable price. Well, you can make it easier if you follow a proper guideline. Here is what you need to know about buying a reconditioned or used smartphone- and a few key questions to ask before you make a purchase.

1. Is It Really Good Idea to Buy a Used or Refurbished Phone?


Of course, it is. Most of the people think that used or reconditioned phones are poor-quality and defective ones. Well, it is not correct. It is a common practice that so many people buy sophisticated smartphones and when they are bored with them, they upgrade them with the latest ones. They return their old phones to the company during the warranty period. And then, they are resold as “Used or Reconditioned Phones” at lower prices. Though these mobile phones are old ones, they don’t have any issues with their functionality.

So, buying such kind of smartphones can be a really good deal since you can grab a good mobile phone of your choice without disturbing your monthly budget.

2. Where Can I Purchase a Second Hand or Refurbished Phone?


Nowadays, there are so many online places where you can buy second hand or refurbished phones from. Let’s have a look at the popular ones:

Classified Ads Websites Like Craigslist


Craigslist is a traditional place that lets you find a lot of money-saving deals on used or reconditioned phones. However, it involves the most risk because you are purchasing directly from an individual seller and don’t get any guarantee or return policy. So, be careful in the selection of a seller.

Auction Websites Such as eBay


Millions of people or companies choose eBay for selling their products including mobile phones. You can easily discover various deals on second hand or refurbished smartphones there. Nevertheless, remember that such types of sites don’t examine the phones and many scammers try to sell their second-rated or defective phones as new or reconditioned ones. So, try to avoid potential scams when buying a phone from eBay or any other auction sites.

Online Retail Shops Like Amazon Trade-in and Gazelle


These marketplaces act as mediators between seller and buyer and guarantee the deal. Further, these sites inspect second hand mobile phones before presenting them for sale, therefore, you are certain to get what you are paying for.

Certified Third-Party Dealers/Sellers


Third-party dealers or sellers are typically approved by smartphone manufacturing companies. Such type of marketplaces offer factory-refurbished and fully tested mobile phones. So, you can buy a nearly new phone at a good discount.

If you want to own a used iPhone, you can explore the refurbished iPhone dealers in UK to avail the best ever deals.

3. Is Any Difference Between a Reconditioned or Used Cell Phone?


Yes. Both are typically different from each other. Used phones are generally sold as-is. That means such mobile phone devices don’t get any refurbishment treatment to restore their fresh condition and functionality. Therefore, they have some scratches and signs of usage or damage, but good in performance if you buy from a reputable seller.

Conversely, reconditioned phones are undergone a complete refurbishment treatment to fix any glitches and to restore their fresh look. This is the reason, such mobile phones not only look like new handsets but also work as good as the new ones.

Bear in mind that used smartphones are usually cheaper than refurbished/reconditioned ones.





4. Is the Mobile Phone Unlocked?


If you are going to buy a second hand or reconditioned phone, you should take into account that either it is locked or unlocked. If you get a locked cell phone, it means that you can’t activate it with any carrier of your choice because it would be locked to some particular carriers. So, try to look for an unlocked mobile phone. Unlocked smartphones enable you to use the services of any preferred network service providers on your gadget.

5. Is the Second Hand Phone Stolen?


If you are purchasing a used or refurbished mobile phone from eBay or Craigslist etc. then it is imperative to make sure that the phone is not stolen or blacklisted. A lot of scamming people use these sites to make money by selling those smartphones that are reported as blacklisted by their real owners; that means these phones have been lost or stolen. Keep in mind that blacklisted phones are not usable.

On the other hand, if you head over to a retail site or a certified dealer’s website to buy a second hand phone, they check the serial number and ensure phones are not stolen before selling. But if you are doing a deal on eBay or Craigslist, you are all alone. So, you should ask the IMEI number from the seller to check that the phone is blacklisted or not.

6. What Condition Is the Second Hand or Refurbished Phone In?


Before buying a used or reconditioned phone, it is obvious to make sure what condition is it in. These phones are generally categorised in different Positions, depending on their condition. Pristine, Excellent, Good, Acceptable, and Refurbished are some terms which are ordinarily used to define the condition of used or reconditioned phones.

Hence, some dealers or sellers also categorise used smartphones in different Grades. Grade A phones not only look like new phones but their quality is also much closer to the new ones, while Grade B and C mobile phones might have some scratches, signs, and marks etc.

7. What’s a Used or Reconditioned Phone Worth?


Don’t become a fool by paying more for less. If you are buying a used or reconditioned phone, it is also key to consider its price. Commonly, second hand or refurbished smartphones are low priced, as much as 50% cheaper than their counterparts. However, the prices depend on the make, model, and condition of the phones. So, before getting attracted towards the cheapest price, inspect the phone condition.

Moreover, never choose the first price you get for a second hand handset. Browse multiple deals and compare them to pick up the best one!

8. Do I Get Warranty on My Used or Refurbished Phone?


It is another key question you must consider before getting a used phone. In general, used phones are not covered under warranty but some sellers provide it. Conversely, reconditioned ones are offered with 90-180 days warranty.

Prefer a seller who offers you a decent warranty and money back guarantee whether you are buying a used or refurbished smartphone.

9. Is Now the Right Time to Purchase a Refurbished or Used Smartphone?


Yes, absolutely! Time is money and you can start looking for various deals on used or reconditioned phones available at different shops today. I am sure, you will definitely find the one that fits your needs and budget. However, it is important to take into consideration that when new models come into the market, the prices of previous versions drop down. So, if you are interested in buying an iPhone X or Samsung Galaxy S8, you can get it in a refurbished condition and save hundreds of pounds since the latest Samsung Galaxy S9 has entered into the market and Apple is also going to launch its three new iPhones in a few coming months.

Thursday, 7 June 2018

Codeigniter Dynamic Dependent Select Box using Ajax


The Dynamic dependent dropdown list box will auto fill data in the select box based on the parent select box selection. This type of dynamic dependent select box mainly used in selection of country-state-city or category-subcategory. It will load dynamic data in dropdown select boxes without refreshing of page then this type of feature will makes our web application more user-friendly. By using Jquery with Ajax we can simply developed this type of dynamic dependent select box feature without refresh of web page.

In this Codeigniter web tutorial, We will learn how can we make dynamic dependent select box or dropdown in Codeigniter by using Ajax with Jquery and Mysql database. For display dynamic dependent dropdown feature, here we will take example of relational select box of country state city in Codeigniter. Here State select box data will be related to country select box and city select box data will be related to state select box. By the selection of dropdown select box of country and state then dependent select box of state and city data will be get from the mysql database without refresh of page by using Ajax with Jquery in Codeigniter.

Here In this example on page load it will displays countries data in country select box. When we have select country then respective states data will be fetched from mysql table and display under the states dropdown without reloading of page. Same way when user has select state from state dropdown then selected state cities data will be fetched from mysql database and fill under city dropdown.



Make Database Tables


For Store data of country, state and city and these three table has been required to created into mysql database. And in all three tables would be connection between country, state and city table. Here first relationship between country and state table and second relationship between city and state table.

Country Table

Below SQL script will makes country table in Mysql Database.


--
-- Database: `country_state_city`
--

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

--
-- Table structure for table `country`
--

CREATE TABLE `country` (
  `country_id` int(11) NOT NULL,
  `country_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `country`
--

INSERT INTO `country` (`country_id`, `country_name`) VALUES
(1, 'USA'),
(2, 'Canada'),
(3, 'Australia'),
(4, 'India');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `country`
--
ALTER TABLE `country`
  ADD PRIMARY KEY (`country_id`);

--
-- AUTO_INCREMENT for dumped tables
--

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


State table

Below SQL script will make state table in your Mysql Database.


--
-- Database: `country_state_city`
--

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

--
-- Table structure for table `state`
--

CREATE TABLE `state` (
  `state_id` int(11) NOT NULL,
  `country_id` int(11) NOT NULL,
  `state_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `state`
--

INSERT INTO `state` (`state_id`, `country_id`, `state_name`) VALUES
(1, 1, 'New York'),
(2, 1, 'Alabama'),
(3, 1, 'California'),
(4, 2, 'Ontario'),
(5, 2, 'British Columbia'),
(6, 3, 'New South Wales'),
(7, 3, 'Queensland'),
(8, 4, 'Karnataka'),
(9, 4, 'Telangana');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `state`
--
ALTER TABLE `state`
  ADD PRIMARY KEY (`state_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `state`
--
ALTER TABLE `state`
  MODIFY `state_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;


City table

Below SQL script will make city table in your Mysql Database.


--
-- Database: `country_state_city`
--

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

--
-- Table structure for table `city`
--

CREATE TABLE `city` (
  `city_id` int(11) NOT NULL,
  `state_id` int(11) NOT NULL,
  `city_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `city`
--

INSERT INTO `city` (`city_id`, `state_id`, `city_name`) VALUES
(1, 1, 'New York city'),
(2, 1, 'Buffalo'),
(3, 1, 'Albany'),
(4, 2, 'Birmingham'),
(5, 2, 'Montgomery'),
(6, 2, 'Huntsville'),
(7, 3, 'Los Angeles'),
(8, 3, 'San Francisco'),
(9, 3, 'San Diego'),
(10, 4, 'Toronto'),
(11, 4, 'Ottawa'),
(12, 5, 'Vancouver'),
(13, 5, 'Victoria'),
(14, 6, 'Sydney'),
(15, 6, 'Newcastle'),
(16, 7, 'City of Brisbane'),
(17, 7, 'Gold Coast'),
(18, 8, 'Bangalore'),
(19, 8, 'Mangalore'),
(20, 9, 'Hydrabad'),
(21, 9, 'Warangal');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `city`
--
ALTER TABLE `city`
  ADD PRIMARY KEY (`city_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `city`
--
ALTER TABLE `city`
  MODIFY `city_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;





Dynamic_dependent.php(Controller)


Here this Dynamic_dependent Contollers has 4 functions like __construct(), index(), fetch_state() and fetch_city().

  • __construct() - This function has been load Dynamic dependent model.
  • index() - This function has retrived country data from mysql database using Dyamic dependent model and pass this data to view file.
  • fetch_state() - This function retrived state data from mysql database based on country id using dynamic dependent model and return data in html format to ajax request.
  • fetch_city() - This function has retrived city data from mysql databse based on state id using dynamic dependent model and return data in html format to ajax request.


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

class Dynamic_dependent extends CI_Controller {
 
 public function __construct()
 {
  parent::__construct();
  $this->load->model('dynamic_dependent_model');
 }

 function index()
 {
  $data['country'] = $this->dynamic_dependent_model->fetch_country();
  $this->load->view('dynamic_dependent', $data);
 }

 function fetch_state()
 {
  if($this->input->post('country_id'))
  {
   echo $this->dynamic_dependent_model->fetch_state($this->input->post('country_id'));
  }
 }

 function fetch_city()
 {
  if($this->input->post('state_id'))
  {
   echo $this->dynamic_dependent_model->fetch_city($this->input->post('state_id'));
  }
 }
  
}


Dynamic_dependent_model.php(Model)


This Dynamic dependent model has four functions like fetch_country(), fetch_state($country_id) and fetch_city($state_id).

  • fetch_country() - This function fetch data from Mysql database and return result data in PHP object.
  • fetch_state($country_id) - This function fetch data from Mysql database based on value of country id and return back data in html format.
  • fetch_city($state_id) - This function fetch city data from Mysql databse based on value of state id and return back data city data in html format.


<?php
class Dynamic_dependent_model extends CI_Model
{
 function fetch_country()
 {
  $this->db->order_by("country_name", "ASC");
  $query = $this->db->get("country");
  return $query->result();
 }

 function fetch_state($country_id)
 {
  $this->db->where('country_id', $country_id);
  $this->db->order_by('state_name', 'ASC');
  $query = $this->db->get('state');
  $output = '<option value="">Select State</option>';
  foreach($query->result() as $row)
  {
   $output .= '<option value="'.$row->state_id.'">'.$row->state_name.'</option>';
  }
  return $output;
 }

 function fetch_city($state_id)
 {
  $this->db->where('state_id', $state_id);
  $this->db->order_by('city_name', 'ASC');
  $query = $this->db->get('city');
  $output = '<option value="">Select City</option>';
  foreach($query->result() as $row)
  {
   $output .= '<option value="'.$row->city_id.'">'.$row->city_name.'</option>';
  }
  return $output;
 }
}

?>


dynamic_dependent.php(View)


This output file of Dynamic Dependent select box and it will display country state and city dropdown on web page. In this file we have use Javascript library jquery and Bootstrap library. In this file you can find that how country dropdown has been fill with data which it has get from controller and fill into country select box. Here State and City dropdown has been blank because it is dynamic and it will fill with data when we have select country select box.

In Jquery code you can find when we have select country from country dropdown, then selected country id has been pass as data to controller and fetch_state() method of controller will fetch state data based on selected country id from mysql databse by using model and that model return state data in html format which has send by controller to ajax request and filled into state dynamic dropdown.

Same way in state dropdown also, when we have select state from state select box, then in ajax request it has pass state id as data to fetch_city() controller method and that method will fetch city data based on value of state id from mysql database by using model and that model return city data in html format and after this controller has return that data to ajax request and it will fill city dynamic dropdown with data.


<html>
<head>
    <title>Codeigniter Dynamic Dependent Select Box using Ajax</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 <style>
 .box
 {
  width:100%;
  max-width: 650px;
  margin:0 auto;
 }
 </style>
</head>
<body>
 <div class="container box">
  <br />
  <br />
  <h3 align="center">Codeigniter Dynamic Dependent Select Box using Ajax</h3>
  <br />
  <div class="form-group">
   <select name="country" id="country" class="form-control input-lg">
    <option value="">Select Country</option>
    <?php
    foreach($country as $row)
    {
     echo '<option value="'.$row->country_id.'">'.$row->country_name.'</option>';
    }
    ?>
   </select>
  </div>
  <br />
  <div class="form-group">
   <select name="state" id="state" class="form-control input-lg">
    <option value="">Select State</option>
   </select>
  </div>
  <br />
  <div class="form-group">
   <select name="city" id="city" class="form-control input-lg">
    <option value="">Select City</option>
   </select>
  </div>
 </div>
</body>
</html>
<script>
$(document).ready(function(){
 $('#country').change(function(){
  var country_id = $('#country').val();
  if(country_id != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>dynamic_dependent/fetch_state",
    method:"POST",
    data:{country_id:country_id},
    success:function(data)
    {
     $('#state').html(data);
     $('#city').html('<option value="">Select City</option>');
    }
   });
  }
  else
  {
   $('#state').html('<option value="">Select State</option>');
   $('#city').html('<option value="">Select City</option>');
  }
 });

 $('#state').change(function(){
  var state_id = $('#state').val();
  if(state_id != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>dynamic_dependent/fetch_city",
    method:"POST",
    data:{state_id:state_id},
    success:function(data)
    {
     $('#city').html(data);
    }
   });
  }
  else
  {
   $('#city').html('<option value="">Select City</option>');
  }
 });
 
});
</script>


Lastly, in this post we have make dynamic dependent dropdown in Codeigniter using country, state and city example. By using this type of example we can easily create relational dropdown whichever type of dynamic data.

Wednesday, 6 June 2018

Ajax Autocomplete Textbox in Laravel using JQuery



In this post we are going to learn ajax live search or make autocomplete textbox by using JQuery in Laravel Application. Here we will make simple and good example of How to create Autocomplete textbox in Ajax JQuery using Laravel. We will use ajax request for getting records from Mysql database table. In tutorial we have build autocomplete functionality in Laravel by using Ajax with Jquery and Mysql database.

For learn Ajax Autocomplete textbox in Laravel we have use simple country search example. In Mysql table we have already inserted all countries name. So, From Laravel application when use has start to type any country name then it will send trigger ajax request to Laravel method for search and get list of country which start with character which has type in textbox by user. And user will get list of country name suggestion below textbox and he can select particular country from list of country. This is main benifites of Autocomplete feature in our web application, we do want to type whole name but we can simply select from list of suggestion.

So, in this post we have make ajax autocomplete textbox in laravel by using JQuery and Mysql database. Below you can find complete step by step process for developed autocomplete textbox feature in Laravel by using Ajax, JQuery and Mysql Database.







Step 1 : Create table in Mysql


First we have to make apps_countries table in our mysql database. We will fetch country data from this table and display in autocomplete country list below textbox.


--
-- Database: `testing`
--

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

--
-- Table structure for table `apps_countries`
--

CREATE TABLE `apps_countries` (
  `id` int(11) NOT NULL,
  `country_code` varchar(2) NOT NULL DEFAULT '',
  `country_name` varchar(100) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Dumping data for table `apps_countries`
--

INSERT INTO `apps_countries` (`id`, `country_code`, `country_name`) VALUES
(1, 'AF', 'Afghanistan'),
(2, 'AL', 'Albania'),
(3, 'DZ', 'Algeria'),
(4, 'DS', 'American Samoa'),
(5, 'AD', 'Andorra'),
(6, 'AO', 'Angola'),
(7, 'AI', 'Anguilla'),
(8, 'AQ', 'Antarctica'),
(9, 'AG', 'Antigua and Barbuda'),
(10, 'AR', 'Argentina'),
(11, 'AM', 'Armenia'),
(12, 'AW', 'Aruba'),
(13, 'AU', 'Australia'),
(14, 'AT', 'Austria'),
(15, 'AZ', 'Azerbaijan'),
(16, 'BS', 'Bahamas'),
(17, 'BH', 'Bahrain'),
(18, 'BD', 'Bangladesh'),
(19, 'BB', 'Barbados'),
(20, 'BY', 'Belarus'),
(21, 'BE', 'Belgium'),
(22, 'BZ', 'Belize'),
(23, 'BJ', 'Benin'),
(24, 'BM', 'Bermuda'),
(25, 'BT', 'Bhutan'),
(26, 'BO', 'Bolivia'),
(27, 'BA', 'Bosnia and Herzegovina'),
(28, 'BW', 'Botswana'),
(29, 'BV', 'Bouvet Island'),
(30, 'BR', 'Brazil'),
(31, 'IO', 'British Indian Ocean Territory'),
(32, 'BN', 'Brunei Darussalam'),
(33, 'BG', 'Bulgaria'),
(34, 'BF', 'Burkina Faso'),
(35, 'BI', 'Burundi'),
(36, 'KH', 'Cambodia'),
(37, 'CM', 'Cameroon'),
(38, 'CA', 'Canada'),
(39, 'CV', 'Cape Verde'),
(40, 'KY', 'Cayman Islands'),
(41, 'CF', 'Central African Republic'),
(42, 'TD', 'Chad'),
(43, 'CL', 'Chile'),
(44, 'CN', 'China'),
(45, 'CX', 'Christmas Island'),
(46, 'CC', 'Cocos (Keeling) Islands'),
(47, 'CO', 'Colombia'),
(48, 'KM', 'Comoros'),
(49, 'CG', 'Congo'),
(50, 'CK', 'Cook Islands'),
(51, 'CR', 'Costa Rica'),
(52, 'HR', 'Croatia (Hrvatska)'),
(53, 'CU', 'Cuba'),
(54, 'CY', 'Cyprus'),
(55, 'CZ', 'Czech Republic'),
(56, 'DK', 'Denmark'),
(57, 'DJ', 'Djibouti'),
(58, 'DM', 'Dominica'),
(59, 'DO', 'Dominican Republic'),
(60, 'TP', 'East Timor'),
(61, 'EC', 'Ecuador'),
(62, 'EG', 'Egypt'),
(63, 'SV', 'El Salvador'),
(64, 'GQ', 'Equatorial Guinea'),
(65, 'ER', 'Eritrea'),
(66, 'EE', 'Estonia'),
(67, 'ET', 'Ethiopia'),
(68, 'FK', 'Falkland Islands (Malvinas)'),
(69, 'FO', 'Faroe Islands'),
(70, 'FJ', 'Fiji'),
(71, 'FI', 'Finland'),
(72, 'FR', 'France'),
(73, 'FX', 'France, Metropolitan'),
(74, 'GF', 'French Guiana'),
(75, 'PF', 'French Polynesia'),
(76, 'TF', 'French Southern Territories'),
(77, 'GA', 'Gabon'),
(78, 'GM', 'Gambia'),
(79, 'GE', 'Georgia'),
(80, 'DE', 'Germany'),
(81, 'GH', 'Ghana'),
(82, 'GI', 'Gibraltar'),
(83, 'GK', 'Guernsey'),
(84, 'GR', 'Greece'),
(85, 'GL', 'Greenland'),
(86, 'GD', 'Grenada'),
(87, 'GP', 'Guadeloupe'),
(88, 'GU', 'Guam'),
(89, 'GT', 'Guatemala'),
(90, 'GN', 'Guinea'),
(91, 'GW', 'Guinea-Bissau'),
(92, 'GY', 'Guyana'),
(93, 'HT', 'Haiti'),
(94, 'HM', 'Heard and Mc Donald Islands'),
(95, 'HN', 'Honduras'),
(96, 'HK', 'Hong Kong'),
(97, 'HU', 'Hungary'),
(98, 'IS', 'Iceland'),
(99, 'IN', 'India'),
(100, 'IM', 'Isle of Man'),
(101, 'ID', 'Indonesia'),
(102, 'IR', 'Iran (Islamic Republic of)'),
(103, 'IQ', 'Iraq'),
(104, 'IE', 'Ireland'),
(105, 'IL', 'Israel'),
(106, 'IT', 'Italy'),
(107, 'CI', 'Ivory Coast'),
(108, 'JE', 'Jersey'),
(109, 'JM', 'Jamaica'),
(110, 'JP', 'Japan'),
(111, 'JO', 'Jordan'),
(112, 'KZ', 'Kazakhstan'),
(113, 'KE', 'Kenya'),
(114, 'KI', 'Kiribati'),
(115, 'KP', 'Korea, Democratic People\'s Republic of'),
(116, 'KR', 'Korea, Republic of'),
(117, 'XK', 'Kosovo'),
(118, 'KW', 'Kuwait'),
(119, 'KG', 'Kyrgyzstan'),
(120, 'LA', 'Lao People\'s Democratic Republic'),
(121, 'LV', 'Latvia'),
(122, 'LB', 'Lebanon'),
(123, 'LS', 'Lesotho'),
(124, 'LR', 'Liberia'),
(125, 'LY', 'Libyan Arab Jamahiriya'),
(126, 'LI', 'Liechtenstein'),
(127, 'LT', 'Lithuania'),
(128, 'LU', 'Luxembourg'),
(129, 'MO', 'Macau'),
(130, 'MK', 'Macedonia'),
(131, 'MG', 'Madagascar'),
(132, 'MW', 'Malawi'),
(133, 'MY', 'Malaysia'),
(134, 'MV', 'Maldives'),
(135, 'ML', 'Mali'),
(136, 'MT', 'Malta'),
(137, 'MH', 'Marshall Islands'),
(138, 'MQ', 'Martinique'),
(139, 'MR', 'Mauritania'),
(140, 'MU', 'Mauritius'),
(141, 'TY', 'Mayotte'),
(142, 'MX', 'Mexico'),
(143, 'FM', 'Micronesia, Federated States of'),
(144, 'MD', 'Moldova, Republic of'),
(145, 'MC', 'Monaco'),
(146, 'MN', 'Mongolia'),
(147, 'ME', 'Montenegro'),
(148, 'MS', 'Montserrat'),
(149, 'MA', 'Morocco'),
(150, 'MZ', 'Mozambique'),
(151, 'MM', 'Myanmar'),
(152, 'NA', 'Namibia'),
(153, 'NR', 'Nauru'),
(154, 'NP', 'Nepal'),
(155, 'NL', 'Netherlands'),
(156, 'AN', 'Netherlands Antilles'),
(157, 'NC', 'New Caledonia'),
(158, 'NZ', 'New Zealand'),
(159, 'NI', 'Nicaragua'),
(160, 'NE', 'Niger'),
(161, 'NG', 'Nigeria'),
(162, 'NU', 'Niue'),
(163, 'NF', 'Norfolk Island'),
(164, 'MP', 'Northern Mariana Islands'),
(165, 'NO', 'Norway'),
(166, 'OM', 'Oman'),
(167, 'PK', 'Pakistan'),
(168, 'PW', 'Palau'),
(169, 'PS', 'Palestine'),
(170, 'PA', 'Panama'),
(171, 'PG', 'Papua New Guinea'),
(172, 'PY', 'Paraguay'),
(173, 'PE', 'Peru'),
(174, 'PH', 'Philippines'),
(175, 'PN', 'Pitcairn'),
(176, 'PL', 'Poland'),
(177, 'PT', 'Portugal'),
(178, 'PR', 'Puerto Rico'),
(179, 'QA', 'Qatar'),
(180, 'RE', 'Reunion'),
(181, 'RO', 'Romania'),
(182, 'RU', 'Russian Federation'),
(183, 'RW', 'Rwanda'),
(184, 'KN', 'Saint Kitts and Nevis'),
(185, 'LC', 'Saint Lucia'),
(186, 'VC', 'Saint Vincent and the Grenadines'),
(187, 'WS', 'Samoa'),
(188, 'SM', 'San Marino'),
(189, 'ST', 'Sao Tome and Principe'),
(190, 'SA', 'Saudi Arabia'),
(191, 'SN', 'Senegal'),
(192, 'RS', 'Serbia'),
(193, 'SC', 'Seychelles'),
(194, 'SL', 'Sierra Leone'),
(195, 'SG', 'Singapore'),
(196, 'SK', 'Slovakia'),
(197, 'SI', 'Slovenia'),
(198, 'SB', 'Solomon Islands'),
(199, 'SO', 'Somalia'),
(200, 'ZA', 'South Africa'),
(201, 'GS', 'South Georgia South Sandwich Islands'),
(202, 'ES', 'Spain'),
(203, 'LK', 'Sri Lanka'),
(204, 'SH', 'St. Helena'),
(205, 'PM', 'St. Pierre and Miquelon'),
(206, 'SD', 'Sudan'),
(207, 'SR', 'Suriname'),
(208, 'SJ', 'Svalbard and Jan Mayen Islands'),
(209, 'SZ', 'Swaziland'),
(210, 'SE', 'Sweden'),
(211, 'CH', 'Switzerland'),
(212, 'SY', 'Syrian Arab Republic'),
(213, 'TW', 'Taiwan'),
(214, 'TJ', 'Tajikistan'),
(215, 'TZ', 'Tanzania, United Republic of'),
(216, 'TH', 'Thailand'),
(217, 'TG', 'Togo'),
(218, 'TK', 'Tokelau'),
(219, 'TO', 'Tonga'),
(220, 'TT', 'Trinidad and Tobago'),
(221, 'TN', 'Tunisia'),
(222, 'TR', 'Turkey'),
(223, 'TM', 'Turkmenistan'),
(224, 'TC', 'Turks and Caicos Islands'),
(225, 'TV', 'Tuvalu'),
(226, 'UG', 'Uganda'),
(227, 'UA', 'Ukraine'),
(228, 'AE', 'United Arab Emirates'),
(229, 'GB', 'United Kingdom'),
(230, 'US', 'United States'),
(231, 'UM', 'United States minor outlying islands'),
(232, 'UY', 'Uruguay'),
(233, 'UZ', 'Uzbekistan'),
(234, 'VU', 'Vanuatu'),
(235, 'VA', 'Vatican City State'),
(236, 'VE', 'Venezuela'),
(237, 'VN', 'Vietnam'),
(238, 'VG', 'Virgin Islands (British)'),
(239, 'VI', 'Virgin Islands (U.S.)'),
(240, 'WF', 'Wallis and Futuna Islands'),
(241, 'EH', 'Western Sahara'),
(242, 'YE', 'Yemen'),
(243, 'ZR', 'Zaire'),
(244, 'ZM', 'Zambia'),
(245, 'ZW', 'Zimbabwe');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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


Step 2: Crate Controller

After this we want to make one Autocomplete controller for handle http request for Autocomplete textbox. For this we have to write this following command in command prompt.


php artisan make:controller AutocompleteController


Above command will make AutocompleteController.php file in app/Http/Controllers folder. In this file we will write following code. First index() method will html output on web page and dislay textbox for enter country name. When we have enter country name then it will send request to fetch() method for search country name from mysql table.

app/Http/Controllers/AutocompleteController.php


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class AutocompleteController extends Controller
{
    //for create controller - php artisan make:controller AutocompleteController

    function index()
    {
     return view('autocomplete');
    }

    function fetch(Request $request)
    {
     if($request->get('query'))
     {
      $query = $request->get('query');
      $data = DB::table('apps_countries')
        ->where('country_name', 'LIKE', "%{$query}%")
        ->get();
      $output = '<ul class="dropdown-menu" style="display:block; position:relative">';
      foreach($data as $row)
      {
       $output .= '
       <li><a href="#">'.$row->country_name.'</a></li>
       ';
      }
      $output .= '</ul>';
      echo $output;
     }
    }

}


Step 3: Crate View File


Now we want to make view file with name autocomplete.blade.php in resources/view/ folder. This is our output file and we can see output in browser. In this file we have write html code for display textbox for enter country name and jquery code for send ajax request to Laravel Autocomplete controller fetch() method. After fetching data from server it will display list of suggested country below textbox.

resources/views/autocomplete.blade.php


<!DOCTYPE html>
<html>
 <head>
  <title>Ajax Autocomplete Textbox in Laravel using JQuery</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;
   }
  </style>
 </head>
 <body>
  <br />
  <div class="container box">
   <h3 align="center">Ajax Autocomplete Textbox in Laravel using JQuery</h3><br />
   
   <div class="form-group">
    <input type="text" name="country_name" id="country_name" class="form-control input-lg" placeholder="Enter Country Name" />
    <div id="countryList">
    </div>
   </div>
   {{ csrf_field() }}
  </div>
 </body>
</html>

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

 $('#country_name').keyup(function(){ 
        var query = $(this).val();
        if(query != '')
        {
         var _token = $('input[name="_token"]').val();
         $.ajax({
          url:"{{ route('autocomplete.fetch') }}",
          method:"POST",
          data:{query:query, _token:_token},
          success:function(data){
           $('#countryList').fadeIn();  
                    $('#countryList').html(data);
          }
         });
        }
    });

    $(document).on('click', 'li', function(){  
        $('#country_name').val($(this).text());  
        $('#countryList').fadeOut();  
    });  

});
</script>


Step 4: Set Route


This is last step of our tutrial and here we want to set route of AutocompleteController.php index() and fetch() method. For this we have to go to routes/web.php and write following code for set route for this two method.

routes/web.php


<?php


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

Route::get('/autocomplete', 'AutocompleteController@index');
Route::post('/autocomplete/fetch', 'AutocompleteController@fetch')->name('autocomplete.fetch');


This is complete step by step process for implement Ajax Autocomplete textbox feature in Laravel Application using JQuery with Mysql database. If you have query regarding this tutorial, please comment in comment box.

Friday, 1 June 2018

Show Hide Password in Form with AngularJS



In Web development, in some moment we want to require hide show input fields like password, because user should check the password what he has type in password fields at the time of user registration in website or any other type of form in which password field is required. So, If you have use AngularJS javascript framework for website development then you can simple use this tutorial for add feature like toggle password in your website. By this feature user can see password what he has filled in password field. This password hide show feature we have made by simple AngularJS script.

If you have work on any form and in that form you may required to use the password input box. Here we have use Bootstrap CSS library with AngularJS, so by using this library we can use glyphicon icon for make stylish user interface. So, when we want to show password then then we will display eye open icon and when we want to hide password then it will display eye close password. So, user can better understand for what he want to do show and hide password.

For make show hide password text we have use different directives of AngularJS javascript framework. By using the magic of their rich angular directive we can achieve our goal to make show hide password feature in our form. Here we have use simple AngularJS expression with name like inputType in input fields type attribute and when page has load then we have set this expression value to password, so that input fields type will be password on page load and we can not see what we have type into this fields. After this we have make one AngularJS function and this function will see when inputType expression value is password then it will change to text and if inputType expression value is text then it will change to password. So, by using this simple we can make toggle password visibility using AngularJS. Below you can find complete source code and online demo of hide show password using AngularJS.










index.php



<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Show Hide Password in Form with AngularJS</title>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
  <style>
  .form_style
  {
   width: 600px;
   margin: 0 auto;
  }
  </style>
 </head>
 <body>
  
  <div class="container" ng-app="show_hide_password" ng-controller="show_hide_password_controller">
   <br />
   <h2 align="center">Show Hide Password in Form with AngularJS</h2><br />

   <div class="panel panel-default form_style">
    <div class="panel-heading">
     <h3 class="panel-title">Login</h3>
    </div>
    <div class="panel-body">
     <div class="form-group">
      <label>Enter Email</label>
      <input type="text" name="email" class="form-control input-lg" ng-model="email_field" placeholder="Enter Email">
     </div>
     <div class="form-group">
      <label>Enter Password</label>
      <div class="input-group">
       <input type="{{inputType}}" name="password" class="form-control input-lg" ng-model="password_field" placeholder="Enter Password" />
       <span class="input-group-addon">
        <span class="{{showHideClass}}" ng-click="showPassword()" style="cursor:pointer"></span>
       </span>
      </div>
     </div>

    </div>
   </div>

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


<script>
 
 var app = angular.module('show_hide_password', []);

 app.controller('show_hide_password_controller', function($scope){

  $scope.inputType = 'password';
  $scope.showHideClass = 'glyphicon glyphicon-eye-open';

  $scope.showPassword = function(){
   if($scope.password_field != null)
   {
    if($scope.inputType == 'password')
    {
     $scope.inputType = 'text';
     $scope.showHideClass = 'glyphicon glyphicon-eye-close';
    }
    else
    {
     $scope.inputType = 'password';
     $scope.showHideClass = 'glyphicon glyphicon-eye-open';
    }
   }
  };

 });

</script>