Wednesday, 19 September 2018

Add Server-side DataTables Custom Filter using PHP with Ajax



jQuery Datatables when initialized on the HTML table it has automatically make certain valuable feature like data pagination, table column sorting, search all table column data from single textbox, display number of records per page functionality without writing of any line of code or script. So, here we have to discuss how can we remove default DataTables search textbox and make custom serach of filter DataTables data using PHP script with Ajax. Because Default Search box is used for search records of all table column and display on Datatables. But in Web Development, Sometimes we want to required custom search filter for get specific column search onlu not whole table column search. For this in this tutorial, We will learn how can we implement custom search filter into jQuery DataTables by using Ajax with PHP script.

jQuery Datatables Customer Search filter with Server side processing help us to get records based on our choices of data filter. For example from the list of data we want to just filter "Male" gender data only. So we have search search in textbox then it will return female data also. For this we have to required custom search filter in Datatables for increase efficiency of exact search of data. We can implement custom search by using HTML Select box or even textbox also for filter jQuery Datatables data.







Database



--
-- Database: `testing`
--

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

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

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

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

INSERT INTO `tbl_customer` (`CustomerID`, `CustomerName`, `Gender`, `Address`, `City`, `PostalCode`, `Country`) VALUES
(1, 'Maria Anders', 'Female', 'Obere Str. 57', 'Berlin', '12209', 'Germany'),
(2, 'Ana Trujillo', 'Female', 'Avda. de la Construction 2222', 'Mexico D.F.', '5021', 'Mexico'),
(3, 'Antonio Moreno', 'Male', 'Mataderos 2312', 'Mexico D.F.', '5023', 'Mexico'),
(4, 'Thomas Hardy', 'Male', '120 Hanover Sq.', 'London', 'WA1 1DP', 'United Kingdom'),
(5, 'Paula Parente', 'Female', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(6, 'Wolski Zbyszek', 'Male', 'ul. Filtrowa 68', 'Walla', '01-012', 'Poland'),
(7, 'Matti Karttunen', 'Male', 'Keskuskatu 45', 'Helsinki', '21240', 'Finland'),
(8, 'Karl Jablonski', 'Male', '305 - 14th Ave. S. Suite 3B', 'Seattle', '98128', 'United States'),
(9, 'Paula Parente', 'Female', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(10, 'John Koskitalo', 'Male', 'Torikatu 38', 'Oulu', '90110', 'Finland'),
(39, 'Ann Devon', 'Female', '35 King George', 'London', 'WX3 6FW', 'United Kingdom'),
(38, 'Janine Labrune', 'Female', '67, rue des Cinquante Otages', 'Nantes', '44000', 'Finland'),
(37, 'Kathryn Segal', 'Female', 'Augsburger Strabe 40', 'Ludenscheid Gevelndorf', '58513', 'Germany'),
(36, 'Elizabeth Brown', 'Female', 'Berkeley Gardens 12 Brewery', 'London', 'WX1 6LT', 'United Kingdom'),
(30, 'Trina Davidson', 'Female', '1049 Lockhart Drive', 'Barrie', 'ON L4M 3B1', 'Canada'),
(31, 'Jeff Putnam', 'Male', 'Industrieweg 56', 'Bouvignies', '7803', 'Belgium'),
(32, 'Joyce Rosenberry', 'Female', 'Norra Esplanaden 56', 'HELSINKI', '380', 'Finland'),
(33, 'Ronald Bowne', 'Male', '2343 Shadowmar Drive', 'New Orleans', '70112', 'United States'),
(34, 'Justin Adams', 'Male', '45, rue de Lille', 'ARMENTIERES', '59280', 'France'),
(35, 'Pedro Afonso', 'Male', 'Av. dos Lusiadas, 23', 'Sao Paulo', '05432-043', 'Brazil'),
(100, 'Kathryn Segal', 'Female', 'Augsburger Strabe 40', 'Ludenscheid Gevelndorf', '58513', 'Germany'),
(101, 'Tonia Sayre', 'Female', '84 Haslemere Road', 'ECHT', 'AB32 2DY', 'United Kingdom'),
(102, 'Loretta Harris', 'Female', 'Avenida Boavista 71', 'SANTO AMARO', '4920-111', 'Portugal'),
(103, 'Sean Wong', 'Male', 'Rua Vito Bovino, 240', 'Sao Paulo-SP', '04677-002', 'Brazil'),
(104, 'Frederick Sears', 'Male', 'ul. Marysiuska 64', 'Warszawa', '04-617', 'Poland'),
(105, 'Tammy Cantrell', 'Female', 'Lukiokatu 34', 'HAMEENLINNA', '13250', 'Finland'),
(106, 'Megan Kennedy', 'Female', '1210 Post Farm Road', 'Norcross', '30071', 'United States'),
(107, 'Maria Whittaker', 'Female', 'Spresstrasse 62', 'Bielefeld Milse', '33729', 'Germany'),
(108, 'Dorothy Parker', 'Female', '32 Lairg Road', 'NEWCHURCH', 'HR5 5DR', 'United Kingdom'),
(109, 'Roger Rudolph', 'Male', 'Avenida Julio Saul Dias 78', 'PENAFIEL', '4560-470', 'Portugal'),
(110, 'Karen Metivier', 'Female', 'Rua Guimaraes Passos, 556', 'Sao Luis-MA', '65025-450', 'Brazil'),
(111, 'Charles Hoover', 'Male', 'Al. Tysiaclecia 98', 'Warszawa', '03-851', 'Poland'),
(112, 'Becky Moss', 'Female', 'Laivurinkatu 6', 'MIKKELI', '50120', 'Finland'),
(113, 'Frank Kidd', 'Male', '2491 Carson Street', 'Cincinnati', 'KY 45202', 'United States'),
(114, 'Donna Wilson', 'Female', 'Hallesches Ufer 69', 'Dettingen', '73265', 'Germany'),
(115, 'Lillian Roberson', 'Female', '36 Iolaire Road', 'NEW BARN', 'DA3 3FT', 'United Kingdom');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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






database_connection.php



<?php

//database_connection.php

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

?>


index.php




<?php

include('database_connection.php');

$country = '';
$query = "SELECT DISTINCT Country FROM tbl_customer ORDER BY Country ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
 $country .= '<option value="'.$row['Country'].'">'.$row['Country'].'</option>';
}

?>

<html>
 <head>
  <title>Custom Search in jQuery Datatables using PHP Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  
 </head>
 <body>
  <div class="container box">
   <h3 align="center">Custom Search in jQuery Datatables using PHP Ajax</h3>
   <br />
   <div class="row">
    <div class="col-md-4"></div>
    <div class="col-md-4">
     <div class="form-group">
      <select name="filter_gender" id="filter_gender" class="form-control" required>
       <option value="">Select Gender</option>
       <option value="Male">Male</option>
       <option value="Female">Female</option>
      </select>
     </div>
     <div class="form-group">
      <select name="filter_country" id="filter_country" class="form-control" required>
       <option value="">Select Country</option>
       <?php echo $country; ?>
      </select>
     </div>
     <div class="form-group" align="center">
      <button type="button" name="filter" id="filter" class="btn btn-info">Filter</button>
     </div>
    </div>
    <div class="col-md-4"></div>
   </div>
   <div class="table-responsive">
    <table id="customer_data" class="table table-bordered table-striped">
     <thead>
      <tr>
       <th width="20%">Customer Name</th>
       <th width="10%">Gender</th>
       <th width="25%">Address</th>
       <th width="15%">City</th>
       <th width="15%">Postal Code</th>
       <th width="15%">Country</th>
      </tr>
     </thead>
    </table>
    <br />
    <br />
    <br />
   </div>
  </div>
 </body>
</html>

<script type="text/javascript" language="javascript" >
 $(document).ready(function(){
  
  fill_datatable();
  
  function fill_datatable(filter_gender = '', filter_country = '')
  {
   var dataTable = $('#customer_data').DataTable({
    "processing" : true,
    "serverSide" : true,
    "order" : [],
    "searching" : false,
    "ajax" : {
     url:"fetch.php",
     type:"POST",
     data:{
      filter_gender:filter_gender, filter_country:filter_country
     }
    }
   });
  }
  
  $('#filter').click(function(){
   var filter_gender = $('#filter_gender').val();
   var filter_country = $('#filter_country').val();
   if(filter_gender != '' && filter_country != '')
   {
    $('#customer_data').DataTable().destroy();
    fill_datatable(filter_gender, filter_country);
   }
   else
   {
    alert('Select Both filter option');
    $('#customer_data').DataTable().destroy();
    fill_datatable();
   }
  });
  
  
 });
 
</script>


fetch.php



<?php

include('database_connection.php');

$column = array('CustomerName', 'Gender', 'Address', 'City', 'PostalCode', 'Country');

$query = "
SELECT * FROM tbl_customer 
";

if(isset($_POST['filter_gender'], $_POST['filter_country']) && $_POST['filter_gender'] != '' && $_POST['filter_country'] != '')
{
 $query .= '
 WHERE Gender = "'.$_POST['filter_gender'].'" AND Country = "'.$_POST['filter_country'].'" 
 ';
}

if(isset($_POST['order']))
{
 $query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
 $query .= 'ORDER BY CustomerID DESC ';
}

$query1 = '';

if($_POST["length"] != -1)
{
 $query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}

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

$statement->execute();

$number_filter_row = $statement->rowCount();

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

$statement->execute();

$result = $statement->fetchAll();



$data = array();

foreach($result as $row)
{
 $sub_array = array();
 $sub_array[] = $row['CustomerName'];
 $sub_array[] = $row['Gender'];
 $sub_array[] = $row['Address'];
 $sub_array[] = $row['City'];
 $sub_array[] = $row['PostalCode'];
 $sub_array[] = $row['Country'];
 $data[] = $sub_array;
}

function count_all_data($connect)
{
 $query = "SELECT * FROM tbl_customer";
 $statement = $connect->prepare($query);
 $statement->execute();
 return $statement->rowCount();
}

$output = array(
 "draw"       =>  intval($_POST["draw"]),
 "recordsTotal"   =>  count_all_data($connect),
 "recordsFiltered"  =>  $number_filter_row,
 "data"       =>  $data
);

echo json_encode($output);

?>

Saturday, 15 September 2018

Codeigniter - Detect User IP Browser Operating System Details



If you want to get or fetch or collect user information like who has visit your website, so you can do this things very easily if you have use Codeigniter. By using Codeigniter we can easily collect user information like user IP Address, browser details, browser version, operating system which he has use in his computer, we can also detect from which device he has get access our website etc. We can fetch all these user information by using Codeigniter "user_agent" library.

User Agent Library in Codeigniter is one class which help programmer to detect user information about user browser, mobile device or even robot visiting to website also. If you have use simple PHP script from get all these information then it is very difficult but in Codeigniter you have simple load this user_agent library and simple way to fetch all user information. Because we want know who has visit our website, from which region or location our website has been open. So, If any one has do any fraud on our website then we can easily detect particular user based on his information. So, it is required to get such type of user information and this task we can easily do by using Codeigniter User Agent Library.







Source Code


Controllers


application/controllers/UserDetails.php

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

class UserDetails extends CI_Controller {
 
 function index()
 {
  $this->load->library('user_agent');
  $data['browser'] = $this->agent->browser();
  $data['browser_version'] = $this->agent->version();
  $data['os'] = $this->agent->platform();
  $data['ip_address'] = $this->input->ip_address();
  $this->load->view('user_details', $data);
 }
 
}
?>


Views



<!DOCTYPE html>
<html>
<head>
 <title>How to Get User IP, Browser & OS Details in Codeigniter</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>

<body>
 <div class="container">
  <br />
  <h3 align="center">How to Get User IP, Browser & OS Details in Codeigniter</h3>
  <br />
  <div class="table-responsive">
   <table class="table table-bordered table-striped">
    <tr>
     <td><b>IP Address</b></td>
     <td><?php echo $ip_address; ?></td>
    </tr>
    <tr>
     <td><b>Operating System</b></td>
     <td><?php echo $os; ?></td>
    </tr>
    <tr>
     <td><b>Browser Details</b></td>
     <td><?php echo $browser . ' - ' . $browser_version; ?></td>
    </tr>
   </table>
  </div>
 </div>
</body>
</html>

12 Fundamental Actions That Help You Secure Your Website from Hackers

12 Fundamental Actions That Help You Secure Your Website from Hackers


Hacking is a damaging web activity that can turn your server into an interface that will transmit spam email messages to meet certain illegal demands. Such an activity primarily emerges out of a casual attitude on part of website owners who feel that their website can never be hacked. However, this notion is not at all true. Every website can be hacked, causing an immense loss to e-commerce businesses. Given the fact that being safe is better than to feel sorry, here are 12 tips that can prevent your website from getting hacked.

1. "Update" Is The Keyword


Website owners should know for a fact that sites with insecure and outdated software are prone to hacking. Therefore, you should always keep your software updated. Businesses should enable their ‘software update’ option as and when a new CMS (Content Management System) or a plugin is available.

You should also know that hacking is now an automated process. And it is not enough if you initiate weekly or monthly updates since bots constantly look for vulnerable websites. In order to win this battle with bots, you should always update your website as soon as the update is available. WP Updates Notifier is a plugin meant for WordPress websites. This plugin sends an email that an update is now available. Additionally, it is also recommended that you have a website firewall in place to secure your website from hacking disasters. Hence it is very important that you keep your scripts and platform up-to-date.

2. Unlock the Power of "HTTPS"


It is now mandatory for websites to display the HTTPS protocol as a measure of web security. Therefore, it is important that you switch to HTTPS which displays a padlock in the address bar; an indication that your website is safe to communicate and transact. HTTPS is a protocol that demonstrates to visitors that your website comes with an additional encryption standard called the Transport Layer Security (TLS).

HTTPS is also a yardstick of web security, informing the users that your site is supported by a Secure Sockets Layer (SSL) certificate. If you are looking to add an additional layer of security, you can buy cheap SSL certificate from an authorized CA. This way, you are building additional layers of security to your website, insulating it from all types of hacking attacks.

3. Parameterized Queries – The Perfect Solution to SQL Injection Hacks


Website owners should realize that a number of hacking attacks take place on account of SQL injections. An SQL injection emerges when your website has a form that needs to be filled in by visitors to provide information. It is here that you need to keep a close watch on the various fields of the form.

Forms with open fields can attract the attention of hackers who can effortlessly insert any code. Once this is done, they will secure a gateway to your website. It is for this reason that you should take certain steps to secure your site from SQL injection hacks. However, the simplest means would be to employ parameterized queries. These queries will tighten your code with sufficient parameters that cannot be trespassed by hackers.

4. CSP Helps Build A Strong Wall Against XSS Attacks


Content Security Policy (CSP) is a handy tool that can secure your website from cross-site scripting (XSS) attacks. XSS attacks are very common threats to websites. These emerge when hackers try to push damaging JavaScript code on your web pages. This activity harms the visitor pages of your website. In an attempt to safeguard your website from such attacks, you can take the help of CSP.

Through CSP, you can ensure that every function or field that is used for inputting data is made as explicit as possible. That means, you are tightening the code so that hackers cannot slip any infected code on to your webpage. CSP, when added to the header of your webpage will offer an array of directives, informing the browser of safe domains.

5. Complex, Long and Unique Passwords Are Mandatory


If you are of the opinion that strong passwords are required only for financial transactions and email conversations, think twice. The strength of a password is more significant with databases, website servers and admins. A combination of alphabets (upper and lower case), numbers and special characters makes up a strong password. It is important that you have at least 12 password characters so as to secure your website. Another tip here is to avoid having the same password for different website logins. While you create a complex, unique and long password, it is advisable that you keep changing it frequently so that hackers cannot mess with the crucial information of your users.

6. Have A Backup Strategy In Place


A hacked website can throw everything out of gear by wiping out all your data and efforts in building a reliable digital interface. Hence it is always better to be prepared of such damaging activities with certain backup strategies. Given the fact that website owners don’t backup regularly, it is very important that you learn how to avoid your unpatched CMS versions to fall into the hands of hackers. Backing up data and storing it in a place which cannot be accessed by the public is the trick that will protect your site from the damages caused by a hacked website.

7. Secure Your Admin Directories


Admin directories, most of the times become gateways for hackers when they use scripts that can scan all the directories on your web server which are commonly named as ‘login’ or ‘admin’. After that, they will do everything to enter into your folders, ultimately compromising the security of your website. Thus it comes as an intelligent move to rename all your admin folders with random names of your choice so as to conceal them.





8. Website Security Tools Can Also Come To Your Rescue


There are a host of web security tools which are commonly called as Penetration Testing. You can rely on some free tools such as Netsparker, Xenotix XSS Exploit Framework and SecurityHeaders.io. Through these aides, you can effectively check the moves of hackers who try to compromise the security of your website.

9. Selection of The Right Extensions


Website owners are at an advantage to use the extensibility feature of CMS applications. However, there are an array of add-ons, plugins and extensions that offer the same functionality. That means, you need to make the right choice with regard to the apt extension. To arrive at a decision, here are some benchmarks. Checking out the date when the extension was last updated can support your decision to pick that one. If the update of the extension happened a year ago, then there is every chance that the author of the extension was inactive. Such extensions fail to address your functionality needs and are also incompetent to resolve security issues.

The number of installations coupled with the age of the extension are two other parameters that you need to focus on. Selecting an extension that was developed by a reliable developer is recommended. That means, you need to choose only the legitimate sources from which you can download all your themes and extensions. You should also know that the ‘free’ versions come with malware as most of them are pirated. It is best to avoid such versions and subscribe to the ones that support paid downloads.

10. Understand The Importance of File Permissions


To a layman, a file permission states the actual user of the file and the activities that he can perform on it.

A ‘Read’ (4) permission enables the user to simply view the file contents. A ‘Write’ (2) permission, on the other hand, approves him to make changes to the file. The ‘Execute’ (1) permission allows him to run the script or program. Since each file permission is associated with a number, it becomes easy for you to permit multiple permissions simply by adding the numbers. A ‘read-write-execute’ permission can be granted by setting the user permission to 7.

This numerical representation will involve 3 types of users.

  • Owner: Only one user who has created the file can be owner.
  • Group: A bunch of users to whom a file is assigned will be granted the same permission.
  • Public: All other people

You may argue that CMS installations come with default permissions. However, it is advisable to look into the below explanation concerning file and folder permissions that are default to any website.

The commonly used 666 file permission (allowing the owner, group and public the permission to read and write) can be a potential threat to your website information. This permission allows everyone including hackers the permission to mess with your files. Similar is the case with the ‘777’ folder permission (all the 3 groups of users are permitted to execute the script). This permits any visitor to delete your files or add malware code. Such acts can make your website susceptible to hacking attacks. So, you as a website owner should provide the apt permissions to different users so as to safeguard your website information.

11. Permitting Users to Upload Files – A Strict 'No'


Website owners should be very careful when granting the permission to users to upload files on to their sites. When a seemingly safe file is uploaded by a user, there is every possibility that it might have a script that opens your website, once it is executed. If your website supports a file upload form, then you should be extra cautious with all the files that are being uploaded. In an attempt to prevent such uploads robbing off your website information, you should consider installing a firewall.

In the event you are permitting web files to be uploaded on to your website, you should stick to safe transport commands like SSH or SFTP. Another tip would be to mount your website on one server, allowing your database to run on another server. You should also look at restricting physical access to your server. All these tips can prevent your database server to land in the hands of hackers.

12. Actionable Tips About Server Configuration Files


As the owner of a website, you should know about your web server configuration files which are powerful. You will find these files located in the root web directory. nginx.conf is the configuration file for Nginx servers. If you are using an Apache web server, you have the .htaccess configuration file. These configuration files, while permitting you to execute server rules also help you secure your website. Speaking of configuration files, below are certain rules that you need to follow and attach to your web server.

  • Protect Sensitive Files: Under this head, you can come up with certain rules that can safeguard certain folders and files. You need to be watchful about CMS configuration files which are mounted on your web server, storing sensitive information. It is here that your database login details are stored in plain text. Admin areas should also be locked along with restricting the PHP execution for directories that permit uploads and store images.
  • Prevent Browsing of Directories: It should be your prime motive to limit the information that can be accessed by hackers. When you keep a tab on the browsing of directories, you are preventing hackers to view the contents of your directories.

These two rules, once implemented, safeguard your configuration files preventing them to land in the hands of hackers.

Closing Thoughts


Calling for some forethought, the above-mentioned proactive tips can help you improve the security of your website. While informing you of the probable issues that may crop up at any time, it is very important that you tightly secure your website from various corners. This way, you will able to stop the numerous automated hacking attacks on your website in addition to safeguarding your goodwill in the market.

Friday, 14 September 2018

Upgrade process from PHP 5.x to 7.x

Upgrade process from PHP 5.x to 7.x


Many PHP developers are still using PHP 5.x version and have not migrated to the latest PHP 7. The reason behind why developers are still using the previous version relates to the fact that many developers tend to fear about its compatibility with their apps. The first thought that strikes their mind is that whether PHP 7 can support their apps or not. At times, they do also fear about the large migration time their apps would require to migrate on the new PHP version.

Why You Should Update Your Apps From PHP 5 to PHP 7?


PHP is a popular server-side scripting language used by many developers to create awesome functional websites. It is vastly used by the programmers because of its easy to understand structure and strong Object Oriented Programming (OOP) support. As according to a survey, around 82% of the world’s overall web apps uses PHP as their back-end programming language. It is necessary for the servers to power web apps with quick loading speeds. As there are number of users who rely on slow 3G speed, and thus require fast web applications.

According to a survey if a web page takes more than 3 seconds to load, 40% of the users abandon that web page quickly. In contrast to PHP 5.6, PHP 7 offers a vast improvement in performance speed of the apps. It makes applications run more smoothly. Because it has new advanced features which lets web apps optimize with higher speed. PHP 7 also reduces the consumption demands of servers. As its functions are really lightweight and requires less powered servers to run web apps.

In this tutorial, I will demonstrate how to migrate your application from PHP 5 version to PHP 7, starting from upgrading the development environment.

For the purpose of this tutorial, I assume that you have a PHP application installed on a web server. The prerequisites include:

  • PHP 5.x & 7.x

I have used Cloudways managed PHP web Hosting. The Cloudways platform offers a great devstack and allows me to work freely without distracting my attention to any server level issue. You can also try out Cloudways for free, by signing up for an account.

PHP Version Settings


The reason why I have selected Cloudways is that it gives simple 1-click functionality to update PHP versions. If you want to update your PHP5 setup, just navigate to the Settings and Packages tab and select the desired version to update.




PHP 5 Features


PHP 5 is in the development circuit for more than 10 years now. In fact, many applications are still using versions, including PHP 5.2, 5.3 or 5.6. It is because of the reason that PHP5 offers tremendous features such as:

  • Flawless Object oriented programming support.
  • Standard PHP Library (SPL)
  • Closures.
  • Namespaces.
  • Magical methods for metaprogramming.
  • MySQLi - advanced MySQL extension.
  • Cleaner Error handling.
  • Supports XML extensions better.




Things You Should Need to Know About PHP 7


PHP 7 was released on December 3, 2015 with advanced features and improved functionalities. It is comparatively faster than the previous PHP 5 versions, and provides optimized performance for the apps. Some new features of the latest PHP 7 are:

PHP Zend Engine


PHP 4 was released in 1999 and since from then, the platform was powered by Zend engine.

Zend is an open source execution engine which supports PHP 7 and is totally developed in C language. It helps interpreting PHP language and gives ease to the developers to perform developmental jobs. PHP 5.X used Zend Engine II, whereas the new PHP 7 version uses Zend Engine with a code name PHPNG (Next Generations).

Power of Error Handling


PHP developers always finds difficult to handle catchable fatal errors, as it is one challenging job for them. But using Exceptions is the only way developers can resolve these fatal errors. The new Zend engines gives ease to the developers handle fatal errors at the run time, which sometimes becomes unprofessional and risky.

The Exception Base Class is not extended by the Engine Exceptions objects in the new Zend engine. The object shows that the engine despite of using older version's interfaces and data, produces different kinds of exceptions in error handling, which are traditionals and the Engine exceptions.

With PHP 7, web programmers are allowed to catch both of these exceptions by using a new Parent Class called BaseException.

Below is the code and result of Fatal errors emerged due to previous versions shown:

Before



function call_method($object){

 $object->method();

}
call_method(null);



After



try{
call_method(null);
} 
catch (EngineException $e){
 
echo "expection":{$e->getMessage()}\n";
}



Added Support To 64-Bit Windows System


Being a prominent member of LAMP stack, PHP uses native environment of Linux. But running on Windows system is not impossible for PHP as well. Windows has two types of bit systems, one is Windows X86 and the other is X64. PHP 5.x didn't had support of Windows X64. But the new PHP 7.x version efficiently supports Windows X64 bit system, and thus eases developers to work in Windows environment.

Now you can run and compile the language on your Windows X64 Bit systems. PHP 7 now supports all the integers and large files of X64 bit system.

Scalar Type Declaration


Using PHP 5, you can pass parameters in a function with classes, interfaces and array types only. For example, if you want to pass a parameter of a certain string type in a function, then you will have to check within a function like the one shown below:


// php 5
function getrollNo($number) {
    if (! is_integer($number)) {
        throw new Exception("Please ensure the value is a number");
    }

    return $number;
}

getrollNo('students');



With PHP 7, there is no need to perform any extra check. You can simply type your function parameters with desired string, int or any other variable type.


// PHP 7
function getrollNo(int $number) {
    return $number;
}

getrollNo('students');

// Error raised
PHP Fatal error:  Uncaught TypeError: Argument 1 passed to getrollNo() must be of the type integer, string given, called in ....



PHP 7 will throw a Fatal error exception as seen above once you type hint with scalar values.

Array Constants


In PHP 5, only constants defined with the define() method can accept scalar values. On the other hand, in PHP 7, you also get the ease to have constant arrays using the define() method.


// PHP 7
define('Students', [
    'rollnoid' => '11',
    'studentname' => 'Pardeep',
    'studentbatch' => '8B'
]);
echo Students['rollnoid'];
// Result
11



Imports from the Same Namespace


In PHP 7, Group use declaration helps make code shorter and easy to understand. Earlier in PHP 5, if you want to use multiple classes, functions and constants from the same namespace, you have to write the code as follows:


// PHP 5
namespace Unicodeveloper\Emoji;

use Unicodeveloper\Emoji\Exceptions\UnknownMethod;
use Unicodeveloper\Emoji\Exceptions\UnknownEmoji;
use Unicodeveloper\Emoji\Exceptions\UnknownUnicode;

class Unicode{

}



In PHP 7, you can easily group them as shown below:


// PHP 7
namespace Unicodeveloper\Emoji;

use Unicodeveloper\Emoji\Exceptions\{
    UnknownMethod, UnknownEmoji, UnknownUnicode, IsNull, function checkForInvalidEmoji, const INVALID_EMOJI };

class Emoji {

}



Return Type Declaration


In PHP 7, you can use functions to return data types. This feature is available in almost all strong programming languages, but just wasn't available in PHP 5. Now with PHP 7, you can write functions to return certain types of data.


function divideValues(int $firstNumber, int $secondNumber): int {
    $value = $firstNumber / $secondNumber;
    return $value;
}

echo divideValues(8, 9);

// Result
0



In the above mentioned function, we want integer as the return value. Therefore, the default coercive type checking in PHP comes into play here. The value returned from the function should be float and should throw a fatal error, but it is automatically returned into an integer.

Enable strict mode by placing declare(strict_types=1); at the top of the file and run it again. It should throw a PHP Fatal Type error like the one shown below:


PHP Fatal error:  Uncaught TypeError: Return value of divideValues() must be of the type integer, float returned in .....


Strong Type Check


PHP 7 allows coercion for specific operations, such as dealing with numeric strings and other data types.


function getBookNo(int $number) {
    return "This is it: " . $number;
}

echo getBookNo("8");

// Result
This is it: 8



In the above mentioned function, I have passed a string in the parameter and later coerced into an integer. But in PHP 7, you can be strict with your parameters. You can ensure that no automatic conversions could occur by defining a strict mode at the top of your file:


declare(strict_types=1);

function getBookNo(int $number) {
    return "This is it: " . $number;
}

echo getBookNo("8");

// Result

PHP Fatal error:  Uncaught TypeError: Argument 1 passed to getBookNo() must be of the type integer, string given, called in ......



Whenever you pass a float value in PHP 5, it strips out the decimal part and returns you an integer result. On the contrary to this, in PHP 7, you will get a fatal error exception if you try to pass in a float value. This feature becomes impressively important when building financial applications.

Spaceship Operator


A new operator called spaceship operator or combined comparison operator (<=>) is introduced in the new PHP 7 version. Its basic purpose is to sort out and combine comparisons.

Before PHP7:



function order_func($a, $b)
{
return ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
}



After PHP7:



function order_func($a, $b)
{
return $a <=> $b;
}



This is one of the beautiful addition in this latest PHP version which can be used to quickly and conveniently compare two expressions. The operators can be used as follows:

a < = > b

f a is less than b, the expression output would be -1
If a is equal to b, the expression output would be 0
If a is greater than b, the expression output would be 1

Accessing Static Values


In PHP 5.x, if you try to access a static value, you get an error like the one shown below:


class student {
    static $name = 'cw';
}

echo ' student'::$name;

// Result
Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM), expecting ',' or ';' in .....



But in PHP 7.x, it throws no error and works flawlessly.


// PHP 7

class student {
    static $name = 'cw';
}

echo 'foo'::$name;

// Result cw



Add Anonymous Classes


PHP 7 enables the developers to use OOP concept and to use anonymous classes. The concept already exists and used in many Object-oriented languages like C# and Java. The anonymous class – as defined by the name- are the classes with no names. But the object that instantiates has same functionality as an object of a named class.

If we talk about the syntax which is same as what we were using in traditional PHP classes the only difference is the name, which is missing. The advantage of using anonymous class is that it can increase the speed of code and execution time as well, if and only if these classes used in an excellent way. And in the case when a class doesn’t need to be documented.


var_dump(new class(){
 public function __Construct($i){
 $this->i =$i;
       }
}



Migrating Your Apps From PHP 5 to PHP 7


PHP 7 includes significant updates which makes its performance really faster than the previous versions. But migrating your application from older version to new PHP 7 might include several challenges. Yet its reward is quite fruitful, as PHP 7 results in much faster performance and less demand on servers.

While migrating your apps to new PHP 7 version, always make sure that the libraries your project uses are available in PHP 7.

Because you may need to hold off the migration process for a while, if your project libraries aren’t supported in PHP 7. While you can check for alternative solutions including removing the dependency on those particular libraries.

If your app uses PHP 5.5 or 5.6, then you can easily migrate it to new PHP 7. However, if the code of your app is written in PHP 4, then it could might require few syntax moderations. As the one like of constructor functions in PHP 4, which are no longer supported in PHP 7.

Make sure that your code includes unit and integration testing as well, while migrating your app to PHP 7. As identifying these issues first through tests makes sure that they get resolved before popping up as bugs on live screen.

Wrapping Up!


In this blog, I have briefly covered all the new upgrades and enhancements of PHP 7, and how some old features of PHP 5 could be easily upgraded to PHP 7. No doubt, PHP 7 is a right choice to adapt in the wake of advancing development norms. As it has came out with such impressive enhancements which perfectly make it an adequate programming language to develop large scale applications.

Still if you have any further questions regarding this article or new advancements in PHP 7, you can simply write your queries in the comments section below.

Thursday, 13 September 2018

Update Multiple Rows with Checkbox in PHP using Ajax Jquery



Many times we have seen requirement of quickly editing or updating of multiple data into mysql database table. It will process our work fast multiple update of data at the same time instead of editing of data one by one. There are many ways we can update or edit multiple data in a single click of button. But here we have use checkboxes input field, by using checkbox selection we can select multiple rows of data for filter large number of data and tell PHP script particular checkbox selection data only needs for updation. So, With checkboxes we can define multiple rows of data by selection from the list of data.

In this post, We will show you how can we update multiple checkbox selected data to Mysql using PHP with Ajax. If we have use simple PHP script for this task, then it will old style of any web development. Here we have use Ajax which latest style of sending and receiving data from client computer to server without refresh of web page and it has increase the performance of our web application and increase the output of our website. Because updating of multiple data at same time then if we have use simple PHP script then it will take more time in edit of multiple data at the same time. But if we have use Ajax then it will process all backend and it will not display process on web page and after success of process it will display result on web page without refresh of web page. So, here we have use Ajax for update or edit of Multiple Mysql data by using checkbox selection with PHP.

First we want to load or display data on web page, for this we have use Ajax request and make function of fetch data and display on web page in tag at the time of page load. After displaying of all data on web page, we want to make one method for how to convert this table plain text data into editable input fields. For process this task, here we have also use jQuery. By using jQuery functionality when we have checked checkboxes then that selected row of plain text data must be converted into editable HTML input fields with filled value. So when we have select multiple checkboxes then all selected row of data will be converted into editable input field. Now we can edit multiple data for make required changes at the same time and process all data with single click. For this task here we have use Ajax and by using Ajax request we can send multiple data in the form of form data by using jQuery serialize() method and send to PHP script. And in PHP script it will update which every data has been received from Ajax and update multiple data with PHP script.

So, this is whole process in which we have use Ajax, HTML checkboxes, jQuery, PHP and Mysql and make simple and required feature like update of multiple records of Mysql using checkbox selection with Ajax PHP. This is one of the useful method of updating of multiple Mysql table data using checkbox selection with Ajax jquery and PHP. Below you can find complete source code and above you can also find video tutorial in which we have describe step by step process of editing of multiple checkbox selection data using PHP with Ajax.







Source Code


Database



--
-- Database: `testing`
--

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

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

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

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

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






database_connection.php



<?php

//database_connection.php

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

?>


index.php



<html>  
    <head>  
        <title>Update Multiple Mysql Data using Checkbox with Ajax in PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
          
    </head>  
    <body>  
        <div class="container">  
            <br />
   <div class="table-responsive">  
    <h3 align="center">Update Multiple Mysql Data using Checkbox with Ajax in PHP</h3><br />
    <form method="post" id="update_form">
                    <div align="left">
                        <input type="submit" name="multiple_update" id="multiple_update" class="btn btn-info" value="Multiple Update" />
                    </div>
                    <br />
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped">
                            <thead>
                                <th width="5%"></th>
                                <th width="20%">Name</th>
                                <th width="30%">Address</th>
                                <th width="15%">Gender</th>
                                <th width="20%">Designation</th>
                                <th width="10%">Age</th>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </form>
   </div>  
  </div>
    </body>  
</html>  
<script>  
$(document).ready(function(){  
    
    function fetch_data()
    {
        $.ajax({
            url:"select.php",
            method:"POST",
            dataType:"json",
            success:function(data)
            {
                var html = '';
                for(var count = 0; count < data.length; count++)
                {
                    html += '<tr>';
                    html += '<td><input type="checkbox" id="'+data[count].id+'" data-name="'+data[count].name+'" data-address="'+data[count].address+'" data-gender="'+data[count].gender+'" data-designation="'+data[count].designation+'" data-age="'+data[count].age+'" class="check_box"  /></td>';
                    html += '<td>'+data[count].name+'</td>';
                    html += '<td>'+data[count].address+'</td>';
                    html += '<td>'+data[count].gender+'</td>';
                    html += '<td>'+data[count].designation+'</td>';
                    html += '<td>'+data[count].age+'</td></tr>';
                }
                $('tbody').html(html);
            }
        });
    }

    fetch_data();

    $(document).on('click', '.check_box', function(){
        var html = '';
        if(this.checked)
        {
            html = '<td><input type="checkbox" id="'+$(this).attr('id')+'" data-name="'+$(this).data('name')+'" data-address="'+$(this).data('address')+'" data-gender="'+$(this).data('gender')+'" data-designation="'+$(this).data('designation')+'" data-age="'+$(this).data('age')+'" class="check_box" checked /></td>';
            html += '<td><input type="text" name="name[]" class="form-control" value="'+$(this).data("name")+'" /></td>';
            html += '<td><input type="text" name="address[]" class="form-control" value="'+$(this).data("address")+'" /></td>';
            html += '<td><select name="gender[]" id="gender_'+$(this).attr('id')+'" class="form-control"><option value="Male">Male</option><option value="Female">Female</option></select></td>';
            html += '<td><input type="text" name="designation[]" class="form-control" value="'+$(this).data("designation")+'" /></td>';
            html += '<td><input type="text" name="age[]" class="form-control" value="'+$(this).data("age")+'" /><input type="hidden" name="hidden_id[]" value="'+$(this).attr('id')+'" /></td>';
        }
        else
        {
            html = '<td><input type="checkbox" id="'+$(this).attr('id')+'" data-name="'+$(this).data('name')+'" data-address="'+$(this).data('address')+'" data-gender="'+$(this).data('gender')+'" data-designation="'+$(this).data('designation')+'" data-age="'+$(this).data('age')+'" class="check_box" /></td>';
            html += '<td>'+$(this).data('name')+'</td>';
            html += '<td>'+$(this).data('address')+'</td>';
            html += '<td>'+$(this).data('gender')+'</td>';
            html += '<td>'+$(this).data('designation')+'</td>';
            html += '<td>'+$(this).data('age')+'</td>';            
        }
        $(this).closest('tr').html(html);
        $('#gender_'+$(this).attr('id')+'').val($(this).data('gender'));
    });

    $('#update_form').on('submit', function(event){
        event.preventDefault();
        if($('.check_box:checked').length > 0)
        {
            $.ajax({
                url:"multiple_update.php",
                method:"POST",
                data:$(this).serialize(),
                success:function()
                {
                    alert('Data Updated');
                    fetch_data();
                }
            })
        }
    });

});  
</script>


select.php



<?php

//select.php

include('database_connection.php');

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

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

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

 echo json_encode($data);
}

?>


multiple_update.php



<?php

//multiple_update.php

include('database_connection.php');

if(isset($_POST['hidden_id']))
{
 $name = $_POST['name'];
 $address = $_POST['address'];
 $gender = $_POST['gender'];
 $designation = $_POST['designation'];
 $age = $_POST['age'];
 $id = $_POST['hidden_id'];
 for($count = 0; $count < count($id); $count++)
 {
  $data = array(
   ':name'   => $name[$count],
   ':address'  => $address[$count],
   ':gender'  => $gender[$count],
   ':designation' => $designation[$count],
   ':age'   => $age[$count],
   ':id'   => $id[$count]
  );
  $query = "
  UPDATE tbl_employee 
  SET name = :name, address = :address, gender = :gender, designation = :designation, age = :age 
  WHERE id = :id
  ";
  $statement = $connect->prepare($query);
  $statement->execute($data);
 }
}

?>

Sunday, 9 September 2018

Upload Image in Laravel using Ajax



Hi, In this tutorial you can find how to upload image or file on folder by using Ajax in Laravel Framework. In one of our post on Laravel framework, in which we have describe how to upload image file in Laravel with validation with complete source code. If you have seen that post then you can simple way to upload file in Laravel but now if you want to learn file upload with Ajax in Laravel, then from this post you can simple way to learn step by step file upload in Laravel using Ajax.

There are many benifits of using Ajax in Laravel like it will reduce traffic between client and server. Ajax will increase the performance and speed of your Laravel web application. By using Ajax we can send and receive data in lightweight json format. So, there are other more benifits of using Ajax in Laravel application. So, If we have you use Ajax in file upload in Laravel then Ajax will increase our file upload speed and it will upload file without refresh of web page and it will reduce load on our web site.

Uploading File or Image is a basic feature of any web application and it is required in most of the web application. If we have use Laravel framework for our web application development then in web application we want to store profile image, product image etc. So, Laravel provide file upload library and by using it we can store image or file on server. Laravel provide image or file upload with validation like file type image or other type of file, file extension, maximum file size etc. So, We have use Ajax form data object in Laravel for upload file then it will become good of our UI also. So, In this post we will learn you how to upload image using Ajax jQuery in Laravel. Here we have use FormData() object in Ajax for upload image in Laravel with display of success and error message on web page.




Install Laravel Application


Here we have store from scratch, so first we want to Install Laravel application, For this we have to run following command in your terminal or command prompt.


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






Create Controller


This is next step in which we want to create controller in our Laravel application for handle http request for upload file using Ajax. For this we have to write following command in our terminal or command prompt.


php artisan make:controller AjaxUploadController


The above command will make controller file in app/Http/Controllers/AjaxUploadController.php. In this file we have make to method.

  • index() - This is root method of this class and it will load ajax_upload.blade.php file in browser.
  • action() - This method has receive ajax request for upload file on server. In this method first we have validate file using Validator Laravel library and after upload file under images folder. After done upload it will return response in JSON format.

app/Http/Controllers/AjaxUploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;

class AjaxUploadController extends Controller
{
    function index()
    {
     return view('ajax_upload');
    }

    function action(Request $request)
    {
     $validation = Validator::make($request->all(), [
      'select_file' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
     ]);
     if($validation->passes())
     {
      $image = $request->file('select_file');
      $new_name = rand() . '.' . $image->getClientOriginalExtension();
      $image->move(public_path('images'), $new_name);
      return response()->json([
       'message'   => 'Image Upload Successfully',
       'uploaded_image' => '<img src="/images/'.$new_name.'" class="img-thumbnail" width="300" />',
       'class_name'  => 'alert-success'
      ]);
     }
     else
     {
      return response()->json([
       'message'   => $validation->errors()->all(),
       'uploaded_image' => '',
       'class_name'  => 'alert-danger'
      ]);
     }
    }
}
?>


Create View


Once you have make controller then you have to make view file and this file has been load by controller. So, Here we have make view file resources/views/ajax_upload.blade.php. This is html output file and in this file we have use jQuery and Bootstrap library. In this file we have also write Ajax code for send upload file request to Controllers. Here we have use FormData() object for send file to Controller.

resources/views/ajax_upload.blade.php

<!DOCTYPE html>
<html>
 <head>
  <title>Upload Image 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">
   <h3 align="center">Upload Image in Laravel using Ajax</h3>
   <br />
   <div class="alert" id="message" style="display: none"></div>
   <form method="post" id="upload_form" enctype="multipart/form-data">
    {{ csrf_field() }}
    <div class="form-group">
     <table class="table">
      <tr>
       <td width="40%" align="right"><label>Select File for Upload</label></td>
       <td width="30"><input type="file" name="select_file" id="select_file" /></td>
       <td width="30%" align="left"><input type="submit" name="upload" id="upload" class="btn btn-primary" value="Upload"></td>
      </tr>
      <tr>
       <td width="40%" align="right"></td>
       <td width="30"><span class="text-muted">jpg, png, gif</span></td>
       <td width="30%" align="left"></td>
      </tr>
     </table>
    </div>
   </form>
   <br />
   <span id="uploaded_image"></span>
  </div>
 </body>
</html>

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

 $('#upload_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"{{ route('ajaxupload.action') }}",
   method:"POST",
   data:new FormData(this),
   dataType:'JSON',
   contentType: false,
   cache: false,
   processData: false,
   success:function(data)
   {
    $('#message').css('display', 'block');
    $('#message').html(data.message);
    $('#message').addClass(data.class_name);
    $('#uploaded_image').html(data.uploaded_image);
   }
  })
 });

});
</script>


Set Route


Lastly we want to set route of index() and action() method of AjaxUploadController.php Controller. For this we have go to routes/web.php and here we have to set route for both method.


<?php



Route::get('/ajax_upload', 'AjaxUploadController@index');

Route::post('/ajax_upload/action', 'AjaxUploadController@action')->name('ajaxupload.action');


Once you have done all above step the you have to go to terminal or command prompt and write following command. This command will run you laravel application.


php artisan serve


Thursday, 6 September 2018

Client Side Form Validation using Parsley.js with PHP Ajax



Validation of Form Data is a very time consuming task of any web developer. So, for reduce form validation task here we have make this tutorial in which we have describe PHP form validation by using Parsleys.js jQuery library. If you are web developer then you have know form validation has been done at server side and client side also or both side. At client side form validation we mainly use pure javascript or jQuery script and on server side form data validation we have used scripting language like PHP. If you have developed some big web application with multiple forms, then you have to write form validation code for each form and this form validation task will be boring and without form validation web application will not work properly and cannot give proper output of any task. Because if wrong type of data entered into system then will also give wrong output. So, Form validation is very required task in web application development.

For this form validation here we have use Parsleys.js Library has been use with PHP form for validate form data at client side. Parsley is a simple and light weight javascript library mainly for form validation. By using this library we can validate form data very easily and it will validate HTML input fields data without writing any lines of code. This form validation Library mainly use special DOM API with attribute for validate HTML form data. That validation are feature rich and we can easily implement into our form and also make some custom validation also.

Below you can find simple example of HTML form validation has been done by using Parsley.js with Ajax and PHP.










Source Code


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_register`
--

CREATE TABLE `tbl_register` (
  `register_id` int(11) NOT NULL,
  `first_name` varchar(150) NOT NULL,
  `last_name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL,
  `website` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_register`
--
ALTER TABLE `tbl_register`
  ADD PRIMARY KEY (`register_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_register`
--
ALTER TABLE `tbl_register`
  MODIFY `register_id` int(11) NOT NULL AUTO_INCREMENT;


index.php



<html>  
    <head>  
        <title>PHP Form Validation using Parsleys.js Library</title>  
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <script src="http://parsleyjs.org/dist/parsley.js"></script>
    </head>
 <style>
 .box
 {
  width:100%;
  max-width:600px;
  background-color:#f9f9f9;
  border:1px solid #ccc;
  border-radius:5px;
  padding:16px;
  margin:0 auto;
 }
 input.parsley-success,
 select.parsley-success,
 textarea.parsley-success {
   color: #468847;
   background-color: #DFF0D8;
   border: 1px solid #D6E9C6;
 }

 input.parsley-error,
 select.parsley-error,
 textarea.parsley-error {
   color: #B94A48;
   background-color: #F2DEDE;
   border: 1px solid #EED3D7;
 }

 .parsley-errors-list {
   margin: 2px 0 3px;
   padding: 0;
   list-style-type: none;
   font-size: 0.9em;
   line-height: 0.9em;
   opacity: 0;

   transition: all .3s ease-in;
   -o-transition: all .3s ease-in;
   -moz-transition: all .3s ease-in;
   -webkit-transition: all .3s ease-in;
 }

 .parsley-errors-list.filled {
   opacity: 1;
 }
 
 .parsley-type, .parsley-required, .parsley-equalto{
  color:#ff0000;
 }
 
 </style>
    <body>  
        <div class="container">  
            <br />  
            <br />
   <br />
   <div class="table-responsive">  
    <h3 align="center">PHP Form Validation using Parsleys.js Library</h3><br />
    <div class="box">
     <form id="validate_form">
      <div class="row">
       <div class="col-xs-6">
        <div class="form-group">
         <label>First Name</label>
         <input type="text" name="first_name" id="first_name" placeholder="Enter First Name" required data-parsley-pattern="^[a-zA-Z]+$" data-parsley-trigger="keyup" class="form-control" />
        </div>
       </div>
       <div class="col-xs-6">
        <div class="form-group">
         <label>Last Name</label>
         <input type="text" name="last_name" id="last_name" placeholder="Last Name" required data-parsley-pattern="^[a-zA-Z ]+$" data-parsley-trigger="keyup" class="form-control" />
        </div>
       </div>
      </div>
      <div class="form-group">
       <label for="email">Email</label>
       <input type="text" name="email" id="email" placeholder="Email" required data-parsley-type="email" data-parsley-trigger="keyup" class="form-control" />
      </div>
      <div class="form-group">
       <label for="password">Password</label>
       <input type="password" name="password" id="password" placeholder="Password" required data-parsley-length="[8, 16]" data-parsley-trigger="keyup" class="form-control" />
      </div>
      <div class="form-group">
       <label for="cpassword">Confirm Password</label>
       <input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm Password"data-parsley-equalto="#password" data-parsley-trigger="keyup" required class="form-control" />
      </div>
      <div class="form-group">
       <label for="cpassword">Website</label>
       <input type="text" id="website" name="website" placeholder="Website URL" data-parsley-type="url" data-parsley-trigger="keyup" class="form-control" />
      </div>
      <div class="form-group">
       <div class="checkbox">
        <label><input type="checkbox" id="check_rules" name="check_rules" required /> I Accept the Terms & Conditions</label>
       </div>
      </div>
      <div class="form-group">
       <input type="submit" id="submit" name="submit" value="Submit" class="btn btn-success" />
      </div>
     </form>
    </div>
   </div>  
  </div>
    </body>  
</html>  
<script>  
$(document).ready(function(){  
    $('#validate_form').parsley();
 
 $('#validate_form').on('submit', function(event){
  event.preventDefault();
  if($('#validate_form').parsley().isValid())
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:$(this).serialize(),
    beforeSend:function(){
     $('#submit').attr('disabled','disabled');
     $('#submit').val('Submitting...');
    },
    success:function(data)
    {
     $('#validate_form')[0].reset();
     $('#validate_form').parsley().reset();
     $('#submit').attr('disabled',false);
     $('#submit').val('Submit');
     alert(data);
    }
   });
  }
 });
});  
</script>


action.php



<?php

//action.php

sleep(5);

if(isset($_POST['first_name']))
{
 $connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
 
 $data = array(
  ':first_name'  => $_POST['first_name'],
  ':last_name'  => $_POST['last_name'],
  ':email'   => $_POST['email'],
  ':password'   => $_POST['password'],
  ':website'   => $_POST['website']
 );
 
 $query = "
 INSERT INTO tbl_register 
 (first_name, last_name, email, password, website) 
 VALUES (:first_name, :last_name, :email, :password, :website)
 ";
 $statement = $connect->prepare($query);
 if($statement->execute($data))
 {
  echo 'Registration Completed Successfully...';
 }
}

?>