My Blog List

Thursday, 28 July 2016

CRUD in AngularJS With PHP

                  Hi. Already we created a posts for Perfect Validation & Speech Recognition If you missed that check it .  

                             Here, we are going to see the CRUD operations in AngularJS with PHP. Normally we know that operations in PHP. That contains more code and it loads the whole page for the every single process. In the OOP concept by using MVC pattern we can do this oprations in back-end. In the AngularJS we can use the MVC pattern in front-end itself. 

                By using AngularJS we can create this CRUD operations in a single page and it will be more efficient than a normal backend process. In this process we are using Model(Business Logic or DB Queries) only in PHP. 

               In AngularJs we can use the controllers to pass the data to PHP. so we are having the advantage of reusability .
Here am attached the source code for your convenience. 

Preview: 




Let's go to the coding part :

1.Html Code 

<h1>Insert Update Delete</h1>
<div ng-controller="Register">
<form >
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email"name="Email" ng-model="Email"  ng-disabled="obj.idisable"  >
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="text" class="form-control" id="exampleInputPassword1" placeholder="Password" name="password" ng-model="password" >
  </div>

  <button type="submit" value="{{btnName}}" class="btn btn-default" ng-click="insert_data()">{{btnName}}</button>
</form>

<table  class="table table-condensed">
    <thead>
      <tr>
        <th>s_id</th>
        <th>Email</th>
        <th>Password</th>

      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="Detail in Details" >
      <td>{{Detail.s_id}} </td>
        <td>{{Detail.Email}}</td>
        <td>{{Detail.password}}</td>
        <td><button type="button"  class="btn btn-danger" ng-click="delete_data(Detail.s_id);" >Delete</button></td>
         <td><button type="button"  class="btn btn-danger" ng-click="edit_data(Detail.s_id,Detail.Email,Detail.password);" >Edit</button></td>
      </tr>
      
    </tbody>
  </table>
</div>




2.Controllers

//Insert Controller

$scope.insert_data=function(){
$http.post("Server/insert.php",{'Email':$scope.Email,'password':$scope.password,'btnName':$scope.btnName})
.success(function(){
$scope.msg="Data Inserted";
$scope.display_data();

})
}

//Delete Controller
$scope.delete_data=function(s_id){
$http.post("Server/delete.php",{'s_id':s_id})
.success(function(){
$scope.msg="Data Deleted";
$scope.display_data();

})
}


//Update Controller

$scope.obj={'idisable':false};
$scope.btnName="Insert";
$scope.edit_data=function(s_id,Email,password){
$scope.s_id=s_id;
$scope.Email=Email;
$scope.password=password;
$scope.btnName="Update";
$scope.obj.idisable=true;
$scope.display_data();
}

//Display Controller
$scope.display_data=function(){
$http.get("Server/fetch_data.php").success(function(response){
$scope.Details=response;
});

}




3. PHP File:

Connection for DB :
<?php
mysql_connect("localhost","root","123");
mysql_select_db("rajkumar");

?>
Insert.PHP
<?php
include("connection.php");
$data=json_decode(file_get_contents("php://input"));


$btnName=mysql_real_escape_string($data->btnName);
if($btnName=='Insert'){
$Email=mysql_real_escape_string($data->Email);
$password=mysql_real_escape_string($data->password);

mysql_query("INSERT INTO register(`Email`, `password`)VALUES('".$Email."','".$password."')");
}


else{
$Email=mysql_real_escape_string($data->Email);
$password=mysql_real_escape_string($data->password);
mysql_query("UPDATE register SET password='".$password."' WHERE   Email='".$Email."'"); 



}

?>

Delete.PHP

<?php
include("connection.php");
$data=json_decode(file_get_contents("php://input"));
$s_id=$data->s_id;
mysql_query("DELETE FROM register WHERE s_id='".$s_id."' ");
?>

Fetch.php

<?php
include('connection.php');

$sql=mysql_query("SELECT s_id,Email,password FROM register");
if(mysql_num_rows($sql)){
$data=array();
while($row=mysql_fetch_array($sql)){
$data[]=array(
's_id'=>$row['s_id'],
'Email'=>$row['Email'],
'password'=>$row['password']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>




4.Database File:

Rajkumar.SQL

-- phpMyAdmin SQL Dump
-- version 4.2.11
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jul 28, 2016 at 10:13 PM
-- Server version: 5.6.21
-- PHP Version: 5.6.3

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `rajkumar`
--

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

--
-- Table structure for table `register`
--

CREATE TABLE IF NOT EXISTS `register` (
`s_id` int(11) NOT NULL,
  `Username` varchar(200) NOT NULL,
  `Email` varchar(200) NOT NULL,
  `password` varchar(300) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `register`
--
ALTER TABLE `register`
 ADD PRIMARY KEY (`s_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `register`
--
ALTER TABLE `register`
MODIFY `s_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=15;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;

/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


Download Here : Click me

   These type of code is lightweight than normal PHP code. It contains very less(370KB) In size. 

Thank you..! Have a nice Day..!

Wednesday, 20 July 2016

Speech Recognition Module

          Hi Friends. Till now, We saw the various type of validation in the previous posts. Here comes the most interesting part that you will enjoy for sure. That's the speech recognition that works on any languages has, no dependencies and its just 2KB in size.


                               Its a simple small java script library that lets your users can control your site with their voice commands,
It works perfect on all updated browsers that support speech recognition.  Now let's try something for real, Here we will see how to create a ToDoList App step by step,


Step1:

                 It runs only on the server. so you have to install the server on your system.

Npm users:    npm install http-server -g



Alternative : It works on servers like XAMPP & WAMP Etc.

Step2:

You have to enable the pop-ups



//Click to Access your microphone




//Click to allow

Let's go to the coding part :

1.Install AngularJS And  annyang JS

          For NPM users,
                1. npm install angularjs -g
                2. npm install annyang -g

      others,

          1. Angularjs
           2. Annyang 

2.Add Library Files


<script type="text/javascript" src="Lib/angular.min.js"></script>

<script type="text/javascript" src="Lib/annyang.min.js"></script>

        
3.Body


<div  ng-controller="ToDoController">

<form name="frm" ng-submit="addTodo()">
  <div class="form-group">
   <label for="exampleInputNewItem">Say NewItem</label>

    <input type="text" class="form-control" id="exampleInputEmail1"  ng-model="newTodo" name="newtodo" >

  </div>

<button ng-disabled="frm.$invalid" class="btn btn-success">Go</button>


</form>
<br>

<button ng-click="clearselected()"  class="btn btn-danger">     Clear selected 
</button>

<ul>
<li ng-repeat="todo in todos">

<input type="checkbox" ng-model="todo.done">
<span ng-class="{'done':todo.done }">
{{$index+1}}  {{todo.title}}
</span>
</li>
</ul>

</div>


4.Javascript File



<var myApp=angular.module("myApp",[]);

//Creating a TODo

myApp.controller('ToDoController',['$scope',function($scope){
$scope.todos=[

{ 'title':'This is rajkumar',
 'done' :false
}
];

$scope.addTodo=function(){
$scope.todos.push(
{
'title':$scope.newTodo,
'done':false
});
$scope.done="";

};

$scope.clearselected=function(){
$scope.todos=$scope.todos.filter(function(item){
return !item.done
})

};

//Voice command 

var commands={
'new item *val' : function(val){
$scope.newTodo=val;
$scope.addTodo();
$scope.$apply();
},

'check number *val' :function(val){
$scope.todos[parseInt(val)-1].done=true;
$scope.$apply();
},
'remove number *val':function(val){
$scope.todos.splice(parseInt(val)-1,1)
$scope.$apply();
},

'clear Selected':function(){
$scope.clearselected();
$scope.$apply();
},

}
annyang.addCommands(commands);
annyang.debug();
annyang.start();

}]);


                     By using this script, you can navigate through any other pages by the voice commands easily. Also you can control the various functionalities.  

 How it works?

1.say New Item "Anything"  It will be any word that gives some meaning.

2. say Check Number 'any number that are in the list' 

3. say Remove Number 'any number that are in the list'

4. say check number 'any number that are in the list' &  say Clear Selected to delete the selected iteams.


 

Thank You..! Have a nice Day 

Thursday, 30 June 2016

Perfect Validation

              This gonna be a bit longer post than the previous one. I hope everyone should read it till the last. At the end, you will learn about the perfect validation in the lesser code. I am damn sure about that I will explain my best to you.

I will divide the validation into three types :

#Type1:


Validation without Javascript : 

            It is already predefined validation in HTML5. we can easily validate using the HTML tags. I used this trick to win the prizes in intercollegiate meets and symposiums in my academic time.

Example:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form>
    <fieldset>
        <legend>Booking Details</legend>
        <div>
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" value="" aria-describedby="name-format" required="" pattern=[a-zA-Z]+ >
          
        </div>
        <div>
            <label for="email">Email (required):</label>
            <input type="email" id="email" name="email" value="">
        </div>
        <div>
            <label>Website:</label>
            <input type="url" id="website" name="website" value="">
        </div>
        <div>
            <label for="numTickets"><abbr title="Number">No.</abbr> of Tickets (required):</label>
            <input type="number" id="numTickets" name="numTickets" value=""   min="10" max="15">
        </div>
        <div class="submit">
            <input type="submit">
        </div>
    </fieldset>
</form>    
</body>
</html>

       But I wouldn't recommend you to follow this type of validation. Because the internet users live in different locations even somebody lives in the remote villages. So,in that case the HTML5 doesn't work in the obsolete browsers (Not an Updated Browsers ).

Download Source : Click Here 

#Type2: 

Validation with AngularJS :-

              By using AngularJS, We can validate the form in very less code. For example, even in the 3kb of memory space, we can do validation easily.

Example:
     
 <form name="frm">

<span>Enter your Name:</span>

<input type="text" name="name" ng-model="user.name" pattern="[a-zA-Z]+" required ng-minlength="5" ng-maxlength="7"><br>

<span ng-show="frm.name.$dirty && frm.name.$valid">
 Correct value
</span><br>

<span ng-show="frm.name.$dirty && frm.name.$error.pattern">
this is not a name this is number
</span>

<span ng-show="frm.name.$dirty && frm.name.$error.minlength">
 very short character
</span>

<span ng-show="frm.name.$dirty && frm.name.$error.maxlength">
very long character
</span>

<span>Enter your Number:</span>

<input type="number" name="number" ng-model="user.number"     min="5" max="7" required ><br>

<span>Enter your Email:</span>

<input type="email" name="email" ng-model="user.email" required><br>

<span ng-show="frm.email.$dirty && frm.email.$error.requried">
     Required
</span>

<span ng-show="frm.email.$dirty && frm.email.$error.email">
not a email
</span>

<span>Enter your URL:</span>

<input type="url" name="url" ng-model="user.url" required><br>

<span>Enter your Time:</span>

<input type="time" name="time" ng-model="user.time" required><br>

<span>Enter your Date:</span>

<input type="date" name="date" ng-model="user.date" required><br>

<span>Enter your Week:</span>

<input type="week" name="week" ng-model="user.week" required><br>

<button ng-disabled="frm.$invalid">Insert data </button>

</form>

       
Download Source : Click Here 
      
#Type3: 

Validation with AngularJS Additional Module 
(ng-message) :-

                 By comparing those previous two types of the validation, I recommend everyone to do the validation by using this module. I will tell why I prefer this type of validation in the following scenario.
             The name field in the form must be filled only by the string. But if the user tries to type one number in that field, we have to show them the two error messages. (1.pattern & 2.min-length) . Now We got two error messages.(1.pattern & 2.min-length)
But this is not a good way, we can't give the priority to the validation. So we have to use this ng-message module. Here we will see how to set priority in the following code. 

Example:


<form name="frm">
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>

    <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email" ng-model="Email" name="Email" ng-minlength="5" ng-maxlength="25" required>

  </div>

 <div ng-messages="frm.Email.$error" role="alert" class="my-messages" ng-if="frm.Email.$dirty">

    <div ng-message="required" class="some-message">Please enter a value for this field.</div>

    <div ng-message="email">This field must be a valid email address.</div>

    <div ng-message="maxlength">This field can be at most 15 characters long.</div>

     <div ng-message="minlength">This field can be at min 5 characters be filed.</div>

  </div>


<div class="form-group">

    <label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" ng-model="password" name="password" ng-minlength="5" 
    ng-maxlength="15" required >

</div>

<div ng-messages="frm.password.$error" role="alert" ng-if="frm.password.$dirty">

<div ng-message="required">Please enter a value for this field.</div>

<div ng-message="maxlength">This field can be at most 15 characters long.</div>

<div ng-message="minlength">This field can be at min 5 characters be filed.</div>

</div>

<div class="form-group">

    <label for="exampleInputPassword1">Conform Password:</label>
    <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Conform Password" ng-model="password2" name="password2" ng-pattern="password" required ng-minlength="5" 
    ng-maxlength="15">

</div>

<div ng-messages="frm.password2.$error" role="alert" ng-if="frm.password2.$dirty">

        <div ng-message="pattern">Password is Not match</div>

        <div ng-message="required">Please enter a conform password.</div>

        <div ng-message="maxlength">Password is Not match</div>

        <div ng-message="minlength">Password is Not match</div>
</div>


<button type="submit" ng-disabled="frm.$invalid" class="btn btn-default">Submit</button>

</form>


              We can set the priority in this type of validation. By comparing the previous type of AngularJS, it contains lesser code. By doing this type of validation, we can easily animate the validation message. 
             Here, I attached the ng-animate module in the following example, 


 Css Script : 


.ngMessages_animationClass {
    height: 50px;
    width: 350px;
}

.ngMessages_animationClass.ng-active-add {
    transition: 0.3s linear all;
    background-color: red;
}

.ngMessages_animationClass.ng-active {
    background-color: red;
}

.ngMessages_animationClass.ng-inactive-add {
    transition: 0.3s linear all;
    background-color: white;
}

.ngMessages_animationClass.ng-inactive {
    background-color: white;
}

.ngMessageClass {
    color: white;
}

.ngMessageClass.ng-enter {
    transition: 0.3s linear all;
    color: transparent;
}

.ngMessageClass.ng-enter-active {
    color: white;
}

.ngMessageClass.ng-leave {
    transition: 0.3s linear all;
    color: white;
}

.ngMessageClass.ng-leave-active {
    color: transparent;
}

JavaScript file :

var app = angular.module('myApp', ['ngAnimate', 'ngMessages']);

Html File : 



<input ng-model="ngModelSample" id="modelSample" name="modelSample" 

type="password"  ng-minlength="5" ng-maxlength="10" required 

class="ngMessageSample" />



<div ng-messages="messageAnimationForm.modelSample.$error" 

class="ngMessages_animationClass" ng-messages-multiple>


     <div ng-message="minlength" class="ngMessages_animationClass">

                  * It's mandatory at least 5 characters

     </div>



     <div ng-message="maxlength" class="ngMessages_animationClass">

                 * It's mandatory at most 10 characters

      </div>

</div>


Download Source : Click Here 


Some useful Idea on Validation :
        Now am gonna share something which will be useful On the validation. Mostly many people won't need to use this step. But am damn sure to say this it will be more effective if you use this on your coding.
         Now we will see about that directive and how it will function on the code. In case of filling the form like apply passport, We have to fill the various fields on that time, after typed all the necessary fields accidentally we pressed the reload (F5)key or navigation link to another page. so, for that action we need an alert box that contains 'leave this page' or 'stay in this page'. I will provide this code in the following example.

Example :
     
<html ng-app="myForm">
<head>
<script src="http://code.angularjs.org/1.5.6/angular.min.js">
</script>
<script type="text/javascript">
 var myForm =angular.module("myForm", []);
 myForm.directive('reconsider', function() {
 return {
        link: function($scope, elem, attrs) {
         window.onbeforeunload = function(){
           if ($scope.frm.$dirty) {
            return "you are not yet finished this";
            }
           }
$scope.$on('$locationChangeStart', function(event, next,current) {
         if ($scope.frm.$dirty) {
         if(!confirm("you are not yet finished this")) {
         event.preventDefault();
         }
                                }
                });
         }
        };
    });

  myForm.controller('rajkumar',['$scope',function($scope){

        var initial = {text: ''};
        $scope.OurModel = angular.copy(initial);   
  }]);
  </script>
<body>
<a href="http://google.com">google </a>

<div >

    <form name="frm" ng-controller="rajkumar" reconsider>
     <input name="input" ng-model="OurModel.text">
    </form>
    </div>
</body>
</html>


Download Source : Click Here 


ANGULAR UI – Ng-MASK( 3rd Party Library )

                In AngularJS, angular-ui/ ui-mask directive is useful to maintaining the pre-determined pattern sensitive type of data like Mobile No,RationCard, Passport No & Credit Card No)
Basically this type of data contains some pre-determined pattern (Example: Passport no- IND 98765432. In the case of passport no, the first three position must contains the string and the remaining contains the integer.

                     If we wrongly type any number or special characters in the first three positions, it will give the error message likewise in the remaining positions if we type the string, it will not validate to the further pages. 


                       In this type of  validation, we put the Mask directive on an input field so the user can only type pre-determined pattern, it will give more benefits than the other types. Here I attach a some example of sensitive Data (Ration Card Number)

Step:1 --- > Download Angular-mask Lib . 

Install Ng-Mask :  bower install angular-mask --save

Alternative :  Click here


Step:2 --- > Link to <head> tag section  
   (<script type="text/javascript" src="Lib/ngMask.min.js"></script>


Step:3 --- > Add to dependency on main module     
  (var myApp=angular.module("myApp",['ngMessages','ngMask']);



Step:4 --- > Add mask Directive on input filed
 Our Rationcard Pattern is (01/G/0782952)  
<input type="text" class="form-control" name="RationCard"
 mask='dd/A/ddddddd' required  >


Here, 

d-> Only Number
A->Only Caps 

   

Example File

index.html

<html>
<head>
<script type="text/javascript" src="Lib/angular.min.js"></script>
<script type="text/javascript" src="Lib/angular-messages.min.js"></script>

<script type="text/javascript" src="Lib/ngMask.min.js"></script>
</head>


<body>
<div class="form-group">
    <label for="exampleInputEmail1">Enter Your RationCard:(01/G/0782952)</label>
    <input type="text" class="form-control" id="exampleInputName" placeholder="01/G/0782952" ng-model="RationCard" name="RationCard" mask-clean="true" mask='dd/A/ddddddd' required  >
  </div>

<div ng-messages="frm.RationCard.$error" role="alert" ng-if="frm.RationCard.$dirty" style="color:maroon"> 
  <div ng-message="mask">RationCard is should be comes (01/G/0782952) this format</div>
         <div ng-message="required" class="ngMessagesClass">RationCard is must fill</div>
      


  </div>

<button type="submit" ng-disabled="frm.$invalid" class="btn btn-default" >Submit</button>

</form>

App.js

var myApp=angular.module("myApp",['ngMessages','ngMask']);


Common Patterns

'*' => /./
Any single character

'w' => /\w/
Any word character (letter, number, underscore)

'W' => /\W/
Any nonword
character

'd' => /\d/
Any digit

'D' => /\D/
Any nondigit

's' => /\s/
Any whitespace character

'S' => /\S/
Any nonwhitespace
character

Download Source : Click Here 


Thank you..! Have a nice Day  :) 

Content Writer : Ganesh