article

Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Tuesday, December 14, 2021

AngularJS Form Validation with Bootstrap

AngularJS Form Validation with bootstrap

Angular Form Properties:

Property Name Description

$valid         This property tells that the form/input field value is valid. True/False.
$invalid         This property tells that the form/input field value is invalid. True/False.
$pristine         This boolean property tells that the form/input has not been used/modified yet.
$dirty         This boolean property tells that the form/input has been used/modified.
$touched         This boolean property says that input field is touched (applied only for input).
$untouched This boolean property says that input field is not touched yet (applied only for input).
$submitted This boolean property says that the form is submitted (applied only for form).


Classes:

Class Name Description

ng-valid         The input filed content is valid.
ng-invalid The input filed content is not valid.
ng-pristine The form/ input field has not been modified/used yet.
ng-dirty         The form/ input field has been modified/used.
ng-touched The input field has been touched.
ng-untouched The input field has not been touched yet.
//formvalidation.html
<!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="validationApp" ng-controller="mainController">
<div class="container" style="width:600px">
    <div class="page-header"><h1>AngularJS Form Validation</h1></div>
    <form name="loginForm" ng-submit="submitForm(loginForm.$valid)" novalidate>
        <div class="form-group" ng-class="{ 'has-error' : loginForm.name.$invalid && !loginForm.name.$pristine }">
            <label>Name*</label>
            <input type="text" name="name" class="form-control" ng-model="name" ng-minlength="3" ng-maxlength="8" required>
            <p ng-show="loginForm.name.$dirty && loginForm.name.$error.required" class="help-block">Name is required</p>
            <p ng-show="loginForm.name.$error.minlength" class="help-block">Name is too short.</p>
            <p ng-show="loginForm.name.$error.maxlength" class="help-block">Name is too long.</p>
        </div>         
        <div class="form-group" ng-class="{ 'has-error' : loginForm.userName.$invalid && !loginForm.userName.$pristine }">
            <label>UserName(email)*</label>
            <input type="email" name="userName" class="form-control" ng-model="userName">
            <p ng-show="loginForm.userName.$invalid && !loginForm.userName.$pristine" class="help-block">Enter a valid email.</p>
        </div>
        <div class="form-group" ng-class="{ 'has-error' : loginForm.password.$invalid && !loginForm.password.$pristine }">
            <label>Password*</label>
            <input type="password" name="password" class="form-control" ng-model="password" ng-minlength="6" ng-maxlength="8" required>
            <p ng-show="loginForm.password.$invalid && !loginForm.password.$pristine" class="help-block">Password must be between 6-8 characters.</p>
        </div>        
        <button type="submit" class="btn btn-primary" ng-disabled="loginForm.$invalid">Submit</button>        
    </form>
    </div>
<script>
var validationApp = angular.module('validationApp', []);

validationApp.controller('mainController', function($scope) {

	// function to submit the form after all validation has occurred			
	$scope.submitForm = function(isValid) {

		// check to make sure the form is completely valid
		if (isValid) { 
			alert('Login Form is valid');
		}
	};
});
</script>
</body>
</html>

AngularJS Live Data Search with PHP Mysql and bootstrap

AngularJS Live Data Search with PHP Mysql and bootstrap

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`) VALUES
(1, 'Tiger Wood', 'Accountant', 'Tokyo', 36, 5689),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654),
(5, 'Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465),
(6, 'Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456),
(9, 'Airi Satou updated', 'Pre-Sales Support updated', 'New York', 25, 4568),
(10, 'Angelica Ramos updated', 'Sales Assistant updated', 'New York', 45, 456),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545),
(19, 'Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468),
(20, 'Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646),
(21, 'Shad Decker', 'Regional Director', 'Tokyo', 45, 4545);

ALTER TABLE `employee`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
index.php
//index.php
<!DOCTYPE html>
<html>
 <head>
  <title>AngularJS Live Data Search with PHP Mysql and bootstrap</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.9/angular.min.js"></script>
</head>
<body>
<div class="container" ng-app="angularlivesearch" ng-controller="search_controller" ng-init="fetchData()">
	<br />
	<h3 align="center">AngularJS Live Data Search with PHP Mysql and bootstrap</h3>
	<br />
	<div class="form-group">
		<div class="input-group">
		 <span class="input-group-addon">Search</span>
		 <input type="text" name="search_query" ng-model="search_query" ng-keyup="fetchData()" placeholder="Search" class="form-control" />
		</div>
	</div>
	<br />
	<table class="table table-striped table-bordered">
		<thead>
		 <tr>
		  <th>Name</th>
		  <th>Position</th>
		  <th>office</th>
		  <th>age</th>
		  <th>Salary</th>
		 </tr>
		</thead>
		<tbody>
		 <tr ng-repeat="data in searchData">
		  <td>{{ data.name }}</td>
		  <td>{{ data.position }}</td>
		  <td>{{ data.office }}</td>
		  <td>{{ data.age }}</td>
		  <td>{{ data.salary }}</td>
		 </tr>
		</tbody>
	</table>
</div>
  
<script>
var app = angular.module('angularlivesearch', []);
	app.controller('search_controller', function($scope, $http){
	$scope.fetchData = function(){
		$http({
			method:"POST",
			url:"fetch.php",
			data:{search_query:$scope.search_query}
		}).success(function(data){
			$scope.searchData = data;
		});
	};
});
</script>
</body>
</html>
fetch.php
//fetch.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");

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

$query = '';
$data = array();

if(isset($form_data->search_query))
{
	$search_query = $form_data->search_query;
	 $query = "
	 SELECT * FROM employee 
	 WHERE (name LIKE '%$search_query%' 
	 OR position LIKE '%$search_query%' 
	 OR office LIKE '%$search_query%') 
	";
}else{
	$query = "SELECT * FROM employee ORDER BY name ASC";
}

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

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

?>

Tuesday, December 7, 2021

AngularJS CRUD(Create, Read, Update and Delete) with UI-Router and PHP MySQLi

AngularJS CRUD(Create, Read, Update and Delete) with UI-Router and PHP MySQLi

https://angularjs.org/

HTML is great for declaring static documents, but it falters when we try to use it for declaring dynamic views in web-applications. AngularJS lets you extend HTML vocabulary for your application. 

CND : https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

AngularUI Router https://github.com/angular-ui/ui-router

Angular UI-Router is a client-side Single Page Application routing framework for AngularJS. Routing frameworks for SPAs update the browser's URL as the user navigates through the app.

CDN Minified : http://unpkg.com/@uirouter/angularjs@latest/release/angular-ui-router.min.js

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Airi ', 'Satou', 'Tokyo'),
(2, 'Angelica ', 'Ramos', 'London'),
(3, 'Ashton ', 'Cox', 'San Francisco'),
(4, 'Bradley ', 'Greer', 'London'),
(5, 'Brenden ', 'Wagner', 'San Francisco'),
(6, 'Brielle ', 'Williamson', 'New York');

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;


index.html
//index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>AngularJS CRUD(Create, Read, Update and Delete) with UI-Router and PHP MySQLi</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script src="https://unpkg.com/@uirouter/angularjs@1.0.30/release/angular-ui-router.min.js"></script>
</head>
<body ng-app="appcrudrouter">
<nav class="navbar navbar-inverse" role="navigation">
    <div class="navbar-header">
        <a class="navbar-brand" ui-sref="#">AngularUI Router</a>
    </div>
    <ul class="nav navbar-nav">
        <li><a ui-sref="home">Home</a></li>
        <li><a ui-sref="about">About</a></li>
        <li><a ui-sref="contact">Contact</a></li>
    </ul>
</nav>
<div class="container">
    <h1 class="page-header text-center">AngularJS CRUD(Create, Read, Update and Delete) with UI-Router and PHP MySQLi</h1>
    <div ui-view></div>
</div>
<script>
var app = angular.module('appcrudrouter', ['ui.router']);

app.config(function($stateProvider, $urlRouterProvider) {
    
    $urlRouterProvider.otherwise('/home');
    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: 'pages/home.html',
            controller: 'homeCtrl'
        })
        .state('add', {
            url: '/add',
            templateUrl: 'pages/add.html',
            controller: 'addCtrl'
        })
        .state('edit', {
            url: '/edit/{member:json}',
            templateUrl: 'pages/edit.html',
            controller: 'editCtrl'
        })
        .state('delete', {
            url: '/delete/{member:json}',
            templateUrl: 'pages/delete.html',
            controller: 'deleteCtrl'
        })
      
	    .state('about', {
            url: '/about',
            templateUrl: 'pages/about.html',
             controller: function($scope) {
                $scope.animals = [{id:1,name:'Dog'},
                {id:2,name:'Cat'}];
            }
        })
		
		.state('about.list', {
            url: '/list/:id',
            templateUrl: 'pages/list.html',
            controller: function($scope,$stateParams) {
                $scope.num = $stateParams.id;
            }
        })
});
</script>
<script src="js/homeController.js"></script>
<script src="js/addController.js"></script>
<script src="js/editController.js"></script>
<script src="js/deleteController.js"></script>
<script src="js/memberService.js"></script>
</body>
</html>
js/addController.js
//js/addController.js
'use strict';

app.controller('addCtrl', ['$scope', 'memberService', '$location', function($scope, memberService, $location){
	$scope.error = false;
	//add member
	$scope.add = function(){
		var addmember = memberService.create($scope.member);
		addmember.then(function(response){
			if(response.data.error){
				$scope.error = true;
				$scope.message = response.data.message;
			}
			else{
				console.log(response);
				$location.path('home');
			}
		});
	}

}]);
js/deleteController.js
//js/deleteController.js
'use strict';

app.controller('deleteCtrl', ['$scope', 'memberService', '$location', '$stateParams', function($scope, memberService, $location, $stateParams){
	$scope.error = false;
	$scope.deletemember = $stateParams.member;

	//delete member
	$scope.delete = function(){
		var dmember = memberService.delete($scope.deletemember);
		dmember.then(function(response){
			if(response.data.error){
				$scope.error = true;
				$scope.message = response.data.message;
			}
			else{
				console.log(response);
				$location.path('home');
			}
		});
	}
}]);
js/editController.js
//js/editController.js
'use strict';

app.controller('editCtrl', ['$scope', 'memberService', '$location', '$stateParams', function($scope, memberService, $location, $stateParams){
	$scope.error = false;
	$scope.updatedmember = $stateParams.member;

	//edit member
	$scope.update = function(){
		var updatemember = memberService.update($scope.updatedmember);
		updatemember.then(function(response){
			console.log(response);
			if(response.data.error){
				$scope.error = true;
				$scope.message = response.data.message;
			}
			else{
				console.log(response);
				$location.path('home');
			}
		});
	}

}]);
js/homeController.js
//js/homeController.js
'use strict';

app.controller('homeCtrl', ['$scope', 'memberService', function($scope, memberService){
	//fetch members
	$scope.fetch = function(){
		var members = memberService.read();
		members.then(function(response){
			$scope.members = response.data;
		});
	}

}]);
js/memberService.js
//js/memberService.js
'use strict';

app.factory('memberService', function($http){
	return{
		read: function(){
			var read = $http.get('api/read.php');
			return read;
		},
		create: function(member){
			var add = $http.post('api/add.php', member);
			return add;
		},
		update: function(member){
			var edit = $http.post('api/edit.php', member);
			return edit;
		},
		delete: function(member){
			var del = $http.post('api/delete.php', member);
			return del;
		}
	}
});
pages/home.html
//pages/home.html
<div class="row" ng-init="fetch()">
	<div class="col-md-12">
		<button href="" class="btn btn-primary" ui-sref="add"><i class="fa fa-plus"></i> Add New</button>	
		<table class="table table-bordered table-striped" style="margin-top:10px;">
			<thead>
                <tr>
                    <th>Firstname</th>
                   	<th>Lastname</th>
                    <th>Address</th>
                   	<th width="200">Action</th>
                </tr>
            </thead>
			<tbody>
				<tr ng-repeat="member in members">
					<td>{{ member.firstname }}</td>
					<td>{{ member.lastname }}</td>
					<td>{{ member.address }}</td>
					<td>
						<button type="button" class="btn btn-success" ui-sref="edit({member: member})"><i class="fa fa-edit"></i> Edit</button> 
						<button type="button" class="btn btn-danger" ui-sref="delete({member: member})"> <i class="fa fa-trash"></i> Delete</button>
					</td>
				</tr>
			</tbody>
		</table>
	</div>
</div>
pages/add.html
//pages/add.html
<div class="row">
	<div class="col-sm-6">
		<div class="alert alert-danger text-center" ng-show="error">
			<button type="button" class="close" ng-click="clear()"><span aria-hidden="true">×</span></button>
			<i class="fa fa-warning"></i> {{ message }}
		</div>
		<div class="panel panel-default">
			<div class="panel-body">
				<h3 class="text-center">Add Form</h3>
				<div class="form-group">
					<label>Firstname:</label>
					<input type="text" class="form-control" ng-model="member.firstname">
				</div>
				<div class="form-group">
					<label>Lastname:</label>
					<input type="text" class="form-control" ng-model="member.lastname">
				</div>
				<div class="form-group">
					<label>Address:</label>
					<input type="text" class="form-control" ng-model="member.address">
				</div>
				<button type="button" class="btn btn-primary" ng-click="add()"><i class="fa fa-save"></i> Save</button>
				<button type="button" class="btn btn-default pull-right" ui-sref="home"><i class="fa fa-arrow-left"></i> Back</button>
			</div>
		</div>
	</div>
</div>
pages/edit.html
//pages/edit.html
<div class="row">
	<div class="col-sm-6">
		<div class="alert alert-danger text-center" ng-show="error">
			<button type="button" class="close" ng-click="clear()"><span aria-hidden="true">×</span></button>
			<i class="fa fa-warning"></i> {{ message }}
		</div>
		<div class="panel panel-default">
			<div class="panel-body">
				<h3 class="text-center">Edit Form</h3>
				<div class="form-group">
					<label>Firstname:</label>
					<input type="text" class="form-control" ng-model="updatedmember.firstname">
				</div>
				<div class="form-group">
					<label>Lastname:</label>
					<input type="text" class="form-control" ng-model="updatedmember.lastname">
				</div>
				<div class="form-group">
					<label>Address:</label>
					<input type="text" class="form-control" ng-model="updatedmember.address">
				</div>
				<button type="button" class="btn btn-success" ng-click="update()"><i class="fa fa-check-square-o"></i> Update</button>
				<button type="button" class="btn btn-default pull-right" ui-sref="home"><i class="fa fa-arrow-left"></i> Back</button>
			</div>
		</div>
	</div>
</div>
pages/delete.html
//pages/delete.html
<div class="row">
    <div class="col-sm-6">
        <div class="alert alert-danger text-center" ng-show="error">
            <button type="button" class="close" ng-click="clear()"><span aria-hidden="true">×</span></button>
            <i class="fa fa-warning"></i> {{ message }}
        </div>
        <div class="panel panel-default">
            <div class="panel-body">
                <h4 class="text-center">Are you sure you want to delete</h4>
                <h3 class="text-center">{{ deletemember.firstname + ' ' + deletemember.lastname }}</h3><br>
                <button type="button" class="btn btn-danger" ng-click="delete()"><i class="fa fa-trash"></i> Delete</button>
                <button type="button" class="btn btn-default pull-right" ui-sref="home"><i class="fa fa-arrow-left"></i> Back</button>
            </div>
        </div>
    </div>
</div>
pages/about.html
//pages/about.html
<div>
    <h1>About Page</h1>
    <p>This page demonstrates <span class="text-danger">multiple</span> and <span class="text-danger">named</span> views.</p>
</div>
<div class="row">
       <ul>
        <li ng-repeat="an in animals">
            <a ui-sref="about.list({id:an.id})">{{an.name}}</a>
        </li>
    </ul>
	<div ui-view></div>
</div>
pages/list.html
//pages/list.html
<div ng-if="num == 1"><strong>Dog</strong> is clicked</div>
<div ng-if="num == 2"><strong>Cat</strong> is clicked</div>
api/add.php
//api/add.php
<?php
    include('dbcon.php');
    
    $data = json_decode(file_get_contents("php://input"));

    $out = array('error' => false, 'firstname' => false, 'lastname' => false, 'address' => false);

    $firstname = $data->firstname;
    $lastname = $data->lastname;
    $address = $data->address;

    if(empty($firstname)){
        $out['firstname'] = true;
        $out['message'] = 'Firstname is required'; 
    } 
    elseif(empty($lastname)){
        $out['lastname'] = true;
        $out['message'] = 'Lastname is required'; 
    }
    elseif(empty($address)){
        $out['address'] = true;
        $out['message'] = 'Address is required'; 
    }
    else{
        $sql = "INSERT INTO members (firstname, lastname, address) VALUES ('$firstname', '$lastname', '$address')";
        $query = $conn->query($sql);

        if($query){
            $out['message'] = 'Member Added Successfully';
        }
        else{
            $out['error'] = true;
            $out['message'] = 'Cannot Add Member';
        }
    }
        
    echo json_encode($out);
?>
api/read.php
//api/read.php
<?php
	include('dbcon.php');
	
	$out = array();
	$sql = "SELECT * FROM members";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$out[] = $row;
	}

	echo json_encode($out);
?>
api/edit.php
//api/edit.php
<?php
    include('dbcon.php');
    
    $data = json_decode(file_get_contents("php://input"));

    $out = array('error' => false);

    $firstname = $data->firstname;
    $lastname = $data->lastname;
    $address = $data->address;
    $memid = $data->id;

   	$sql = "UPDATE members SET firstname = '$firstname', lastname = '$lastname', address = '$address' WHERE id = '$memid'";
   	$query = $conn->query($sql);

   	if($query){
   		$out['message'] = 'Member updated Successfully';
   	}
   	else{
   		$out['error'] = true;
   		$out['message'] = 'Cannot update Member';
   	}

    echo json_encode($out);
?>
api/delete.php
//api/delete.php
<?php
    include('dbcon.php');
    
    $data = json_decode(file_get_contents("php://input"));

    $out = array('error' => false);

    $memid = $data->id;

   	$sql = "DELETE FROM members WHERE id = '$memid'";
   	$query = $conn->query($sql);

   	if($query){
   		$out['message'] = 'Member deleted Successfully';
   	}
   	else{
   		$out['error'] = true;
   		$out['message'] = 'Cannot delete Member';
   	}

    echo json_encode($out);
?>
api/dbcon.php
//api/dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Saturday, December 4, 2021

AngularJS Load more data with PHP MySQLi

AngularJS Load more data with PHP MySQLi

CREATE TABLE `posts` (
  `id` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `link` varchar(255) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `posts` (`id`, `title`, `content`, `link`, `timestamp`) VALUES
(4, 'What is AngularJS', 'AngularJS is a JavaScript MVC framework  developed by Google that lets you build well structured, easily testable,  declarative and maintainable front-end applications which provides solutions to  standard infrastructure concerns.', 'link-5', '2021-03-20 08:00:00'),
(5, 'What is MongoDB', 'It is a quick tutorial on MongoDB and how you can install it on your Windows OS. We will also learn some basic commands in MongoDB for example, creating and dropping a Database, Creation of a collection and some more operations related to the collection.', 'link-6', '2021-03-21 08:00:00'),
(6, 'Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb', 'Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb', 'link-6', '2021-03-20 08:00:00'),
(7, 'AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI', 'AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI', 'link-7', '2021-03-14 08:00:00'),
(8, 'PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax', 'PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax', 'link-8', '2021-03-20 08:00:00'),
(9, 'Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql', 'Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql', 'link-9', '2021-03-19 08:00:00'),
(10, 'Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database', 'Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database', 'link-10', '2021-03-15 08:00:00'),
(11, 'Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database', 'Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database', 'link-11', '2021-03-14 08:00:00');

ALTER TABLE `posts`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `posts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>AngularJS Load more data with PHP MySQLi</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.4.8/angular.min.js"></script> 
</head>
<body ng-app="app" ng-controller="myController" ng-init="fetch()">
<div class="container">
    <h1 class="page-header text-center">AngularJS Load more data with PHP MySQLi</h1>
	<div class="col-md-12">
	    <div class="panel panel-default" ng-repeat="rs in posts">
	    	<div class="panel-body">
	    		<span style="font-size:20px">{{ rs.id }} {{ rs.title }}</span>
	    	</div>
		</div>
		<button class="btn btn-success btn-lg btn-block" ng-click="loadmore()">{{ loadName }}</button>
		<br><br>
	</div>
</div>
<script>
var app = angular.module('app', []);
app.controller('myController', function($scope, $http){
	$scope.loadName = 'Load More';
	$scope.fetch = function(){
    	$http.get('fetch.php')
    	.success(function(data){ 
    	    $scope.posts = data;
    	    console.log($scope.posts); 
	    });
    }

    $scope.loadmore = function(){
    	var lastid = $scope.posts.length - 1;
    	var lastobj = $scope.posts[lastid];
    	$http.post('loadmore.php', lastobj)
    	.success(function(data){ 
    		if(data == ''){
    			$scope.loadName = 'No more Data to Load';
    		}
    		else{
    			angular.forEach(data, function(newpost){
					$scope.posts.push(newpost); 
				});
    		}
    	    console.log($scope.posts);
	    });
    }
});
</script>
</body>
</html>
fetch.php
//fetch.php
<?php
	$conn = new mysqli('localhost', 'root', '', 'testingdb');
	
	$output = array();
	$sql = "SELECT * FROM posts ORDER BY id ASC LIMIT 3";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$output[] = $row;
	}

	echo json_encode($output);
?>
loadmore.php
//loadmore.php
<?php
	$conn = new mysqli('localhost', 'root', '', 'testingdb');

	$data = json_decode(file_get_contents('php://input'));
	
	$output = array();

	$id = $data->id;

	$sql = "SELECT * FROM posts WHERE id > '$id' ORDER BY id ASC LIMIT 3";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$output[] = $row;
	}

	echo json_encode($output);
?>

Friday, November 26, 2021

AngularJS Show Alert with Timeout

AngularJS Show Alert with Timeout

index.html
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>AngularJS Create Alert with Timeout</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 type="text/css">
    	.bottom-left{
			display:block;
			position:absolute;
			bottom:50px;
			left:50px;
		}
    </style>
</head>
<body  ng-app="app" ng-controller="myController">
<div class="container">
    <h1 class="page-header text-center">AngularJS Show Alert with Timeout</h1>
    <div class="row">
	    <div class="col-sm-4 col-sm-offset-4">
	    	<div class="panel panel-default">
	    		<div class="panel-body">
	    			<form name="myForm" ng-submit="submitForm()">
	    				<div class="form-group">
		    				<label>User Name:</label>
		    				<input type="text" class="form-control" ng-model="user.username" required>
		    			</div>
		    			<div class="form-group">
		    				<label>Password:</label>
		    				<input type="password" class="form-control" ng-model="user.password" required>
		    			</div>
	    				<button type="submit" class="btn btn-primary" ng-disabled="myForm.$invalid"><span class="glyphicon glyphicon glyphicon-send"></span> Submit</button>
					</form>
	    		</div>
			</div>		
		</div>
	</div>
</div>
<div class="alert alert-success text-center bottom-left" ng-show="success">
	<button type="button" class="close" ng-click="closeAlert()">×</button>
   	<span class="glyphicon glyphicon-check"></span> {{ message }}
</div>
<script>
var app = angular.module('app', []);
app.controller('myController', function($scope, $timeout){
    $scope.success = false;

    $scope.submitForm = function(){
    	//success request
    	$scope.success = true;
    	$scope.message = 'Successfully Login'; 
    	
    	//after 5 sec call to close the alert
    	$timeout( function(){
            $scope.closeAlert();
        }, 5000 );
    }

    $scope.closeAlert = function(){
    	$scope.success = false;
    }
});
</script>
</body>
</html>

Sunday, November 21, 2021

AngularJS Auto complete Textbox

AngularJS Auto complete Textbox

index.html
//index.html
<!DOCTYPE html>  
 <html>  
<head>  
<title>AngularJS Auto complete Textbox</title>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
<style>  
    li{  
        cursor:pointer;  
    }  
    li:hover {  
        background-color:#f9f9f9;  
    }  
</style>  
</head>  
<body>  
<br /><br />  
<div class="container" style="width:600px;">  
    <h1 align="center">AngularJS Auto complete Textbox</h1>  
    <div ng-app="angularautocomplete" ng-controller="membercontroller">  
        <label>Enter Member Name</label>  
        <input type="text" name="members" id="members" ng-model="members" ng-keyup="complete(members)" class="form-control" />  
        <ul class="list-group" ng-model="hidethis" ng-hide="hidethis">  
            <li class="list-group-item" ng-repeat="membersdata in filterMember" ng-click="fillTextbox(membersdata)">{{membersdata}}</li>  
        </ul>  
    </div>  
</div>  
<script>  
	var app = angular.module("angularautocomplete",[]);  
	app.controller("membercontroller", function($scope){  
      $scope.membersList = [  
           "Airi Satou", "Angelica Ramos", "Ashton Cox", "Bradley Greer", "Brenden Wagner", "Brielle Williamson", "Bruno Nash", "Caesar Vance", "Cara Stevens", "Cedric Kelly" 
      ];  
	  
    $scope.complete = function(string){  
        $scope.hidethis = false;  
        var output = [];  
        angular.forEach($scope.membersList, function(members){  
            if(members.toLowerCase().indexOf(string.toLowerCase()) >= 0)  
            {  
                output.push(members);  
            }  
        });  
        $scope.filterMember = output;  
	}  
    $scope.fillTextbox = function(string){  
           $scope.members = string;  
           $scope.hidethis = true;  
    }  
 });  
</script> 
</body>  
</html>  

Angularjs PHP Image Upload With Preview

Angularjs PHP Image Upload With Preview

index.html
//index.html
<!DOCTYPE html>
<html>
<head>
    <title>Angularjs PHP Image Upload With Preview</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="main-App" ng-controller="MemberController">
<div class="container py-5">
    <header class="text-white text-center">
        <h1 class="display-4">Angularjs PHP Image Upload With Preview</h1>
    </header>
    <div class="row py-4">
        <div class="col-lg-6 mx-auto">

			<form ng-submit="submit()" name="form" role="form">
            <div class="input-group mb-3 px-2 py-2 rounded-pill bg-white shadow-sm">
                <input id="upload" ng-model="form.image" type="file" accept="image/*" onchange="angular.element(this).scope().uploadedFile(this)" class="form-control border-0">
                <label id="upload-label" for="upload" class="font-weight-light text-muted">Choose file</label>
                <div class="input-group-append">
                    <label for="upload" class="btn btn-light m-0 rounded-pill px-4"> <i class="fa fa-cloud-upload mr-2 text-muted"></i><small class="text-uppercase font-weight-bold text-muted">Choose file</small></label>
                </div>
            </div>
			
			<input type="submit" id="submit" value="Submit" class="btn btn-info"/>
			
            <!-- Uploaded image area-->
            <p class="font-italic text-white text-center">The image uploaded will be rendered inside the box below.</p>
            <div class="image-area mt-4"><img ng-src="{{image_source}}" alt="" class="img-fluid rounded shadow-sm mx-auto d-block"></div>
			</form>
        </div>
    </div>
</div>
<style>
#upload {
    opacity: 0;
}

#upload-label {
    position: absolute;
    top: 50%;
    left: 1rem;
    transform: translateY(-50%);
}

.image-area {
    border: 2px dashed rgba(255, 255, 255, 0.7);
    padding: 1rem;
    position: relative;
}

.image-area::before {
    content: 'Uploaded image result';
    color: #fff;
    font-weight: bold;
    text-transform: uppercase;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 0.8rem;
    z-index: 1;
}

.image-area img {
    z-index: 2;
    position: relative;
}
body {
    min-height: 100vh;
    background-color: #757f9a;
    background-image: linear-gradient(147deg, #757f9a 0%, #d7dde8 100%);
}
</style>
<script type="text/javascript">
	var app =  angular.module('main-App',[]);
	app.controller('MemberController', function($scope, $http) {

	$scope.form = [];
	$scope.files = [];

	$scope.submit = function() {
	    $scope.form.image = $scope.files[0];
		
		$http({
			method  : 'POST',
			url     : 'upload.php',
			processData: false,
			transformRequest: function (data) { 
			    var formData = new FormData();
			    formData.append("image", $scope.form.image);  
			    return formData;  
			},  
			data : $scope.form,
			headers: {
			       'Content-Type': undefined
			}
		 }).success(function(data){
		    alert(data);
		});
	};

	$scope.uploadedFile = function(element) {
		$scope.currentFile = element.files[0];
		var reader = new FileReader();

		reader.onload = function(event) {
		    $scope.image_source = event.target.result
		    $scope.$apply(function($scope) {
		        $scope.files = element.files;
		      });
		    }
            reader.readAsDataURL(element.files[0]);
		}
	});
	</script>
</body>
</html>
upload.php
//upload.php
<?php
	if(!empty($_FILES['image'])){
		$ext = pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION);
                $image = time().'.'.$ext;
                move_uploaded_file($_FILES["image"]["tmp_name"], 'images/'.$image);
		echo "Profile Image uploaded successfully as ".$image;
	}else{
		echo "Profile Image Is Empty";
	}
?>

Friday, November 19, 2021

AngularJS Dynamic Add Remove Input Fields with PHP and Mysql

AngularJS Dynamic Add Remove Input Fields with PHP and Mysql

CREATE TABLE `skills` (
  `id` int(11) NOT NULL,
  `skillname` varchar(150) NOT NULL,
  `username` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


ALTER TABLE `skills`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `skills`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

index.html
//index.html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Dynamic Add Remove Input Fields with PHP and Mysql</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.9/angular.min.js"></script>
</head>
<body>
<div class="container">
	<div class="col-md-8">
   <h3 align="center">AngularJS Dynamic Add Remove Input Fields with PHP and Mysql</h3>
	<br />
	<div ng-app="angularappaddremovefields" ng-controller="dynamicController" class="container" ng-init="fetchData()">
	   
	<div class="alert alert-success alert-dismissible" ng-show="success" >
		<a href="#" class="close" aria-label="close">×</a>
		{{successMessage}}
	</div>

	<div class="alert alert-danger alert-dismissible" ng-show="error" >
		<a href="#" class="close" aria-label="close">×</a>
		{{errorMessage}}
	</div>

    <form method="post" ng-submit="submitForm()">
		<div class="form-group">
			<label>Enter Your Name</label>
			<input type="text" name="username" id="username" ng-model="formData.username" class="form-control" />
		</div>
	
		<fieldset ng-repeat="row in rows">
		 <div class="form-group">
		  <label>Enter Your Skills</label>
		  <div class="row">
		   <div class="col-md-9">
			<input type="text" name="txtskills[]" class="form-control" ng-model="formData.skill[$index + 1]" />
		   </div>
		   <div class="col-md-3">
			<button type="button" name="remove" ng-model="row.remove" class="btn btn-danger btn-sm" ng-click="removeRow()"><span class="glyphicon glyphicon-minus"></span></button>
		   </div>
		  </div>
		 </div>
		</fieldset>
		<div class="form-group">
		 <button type="button" name="add_more" class="btn btn-success" ng-click="addRow()"><span class="glyphicon glyphicon-plus"></span> Add</button>
		 <input type="submit" name="submit" class="btn btn-info" value="Save" />
		</div>
    </form>

	<div class="table-responsive">
		<table class="table table-bordered table-striped">
		 <tr>
		  <th>Skills</th>
		 </tr>
		 <tr ng-repeat="rs in skillData">
		  <td>{{rs.skillname}}</td>
		 </tr>
		</table>
	</div>
	</div>
  </div>
</div>

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

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

	$scope.success = false;
	$scope.error = false;

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

	$scope.rows = [{username: 'txtskills[]', username: 'remove'}];

	$scope.addRow = function(){
	  var id = $scope.rows.length + 1;
	  $scope.rows.push({'id':'dynamic'+id});
	};

	$scope.removeRow = function(row){
	  var index = $scope.rows.indexOf(row);
	  $scope.rows.splice(index, 1);
	};

	$scope.formData = {};
	$scope.formData.username = "cairocoders";

	$scope.submitForm = function(){
	  $http({
	   method:"POST",
	   url:"insert.php",
	   data:$scope.formData
	  }).success(function(data){ console.log(data);
	   if(data.error != '')
	   {
		$scope.success = false;
		$scope.error = true;
		$scope.errorMessage = data.error;
	   }
	   else
	   {
		$scope.success = true;
		$scope.error = false;
		$scope.successMessage = data.message;
		$scope.formData = {};
		$scope.formData.username = "cairocoders";
		$scope.rows = [{username: 'txtskills[]', username: 'remove'}];
		$scope.fetchData();
	   }
	  });
	};

});
</script>
 </body>
</html>
fetch_data.php
//fetch_data.php
<?php
include('dbcon.php');
$query = "SELECT * FROM skills ORDER BY id";
$statement = $connect->prepare($query);
if($statement->execute())
{
	while($row = $statement->fetch(PDO::FETCH_ASSOC))
	{
	  $data[] = $row;
	}
 echo json_encode($data);
}
?>
insert.php
//insert.php
<?php
include('dbcon.php');

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

$error = '';
$message = '';
$validation_error = '';
$username = '';
$txtskills = '';

$username = $form_data->username;

if(empty($form_data->skill))
{
	$error[] = 'Skill is Required';
}else{
	foreach($form_data->skill as $rs)
	{
	  $txtskills .= $rs . ', ';
	}
	 $txtskills = substr($txtskills, 0, -2);
}

$data = array(
	':username'      => $username,
	':txtskills' => $txtskills
);

if(empty($error))
{
	$query = "
	 INSERT INTO skills 
	 (username, skillname) VALUES 
	 (:username, :txtskills)
	 ";
	 $statement = $connect->prepare($query);
	 if($statement->execute($data))
	 { 
	    $message = 'Data Inserted '.$username.' = '.$txtskills.'';
	 }
}else {
	$validation_error = implode(", ", $error);
}

$output = array(
	 'error'  => $validation_error,
	 'message' => $message
);

echo json_encode($output);
?>
dbcon.php
//dbcon.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");
?>

Saturday, November 13, 2021

AngularJS CRUD (Create, Read, Update and Delete) with PHP Mysql

AngularJS CRUD (Create, Read, Update and Delete) with PHP Mysql

This tutorial used CDN for Bootstrap, Angular JS

index.html
//index.html
<!DOCTYPE html>  
<html>  
<head>  
<title>AngularJS CRUD with PHP Mysql</title>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
</head>  
<body>  
<br /><br />  
<div class="container" style="width:600px;">  
	<h3 align="center">AngularJS CRUD (Create, Read, Update and Delete) with PHP Mysql</h3>  
    <div ng-app="angularcrud" ng-controller="usercontroller" ng-init="displayData()">  
        <label>Name</label>  
        <input type="text" name="txtname" ng-model="txtname" class="form-control" />  
        <br />  
        <label>User Name</label>  
        <input type="text" name="txtusername" ng-model="txtusername" class="form-control" />  
        <br />  
		<input type="hidden" name="txtid" ng-model="id" /> 
        <input type="submit" name="btnInsert" class="btn btn-info" ng-click="insertData()" value="{{btnName}}"/>  
        <br /><br />  
		
        <table class="table table-bordered">  
            <tr>  
                <th>Name</th>  
                <th>User Name</th>  
                <th>Update</th>  
                <th>Delete</th>  
            </tr>  
            <tr ng-repeat="x in names">  
                <td>{{x.fullname}}</td>  
                <td>{{x.username}}</td>  
                <td><button ng-click="updateData(x.userid, x.fullname, x.username)" class="btn btn-info btn-xs">Update</button></td>  
                <td><button ng-click="deleteData(x.userid )"class="btn btn-danger btn-xs">Delete</button></td>  
            </tr>  
        </table>  
    </div>  
</div> 
<script>  
 var app = angular.module("angularcrud",[]);  
 app.controller("usercontroller", function($scope, $http){  
      $scope.btnName = "ADD";  
      $scope.id = 0;  
      $scope.insertData = function(){  
           if($scope.txtname == null)  
           {  
                alert("Name is required");  
           }  
           else if($scope.txtusername == null)  
           {  
                alert("Username is required");  
           }  
           else  
           {  
				$http.post(  
                     "insert_update.php",  
                     {'txtname':$scope.txtname, 'txtusername':$scope.txtusername, 'txtid':$scope.id, 'btnName':$scope.btnName}  
                ).success(function(data){  
                     alert(data);  
                     $scope.txtname = null;  
                     $scope.txtusername = null;  
                     $scope.txtid = null;  
                     $scope.btnName = "ADD";  
                     $scope.displayData();  
                });  
           }  
      }  
      $scope.displayData = function(){  
           $http.get("list.php")  
           .success(function(data){  
                $scope.names = data;  
           });  
      }  
      $scope.updateData = function(id, fullname, username){  
           $scope.id = id;  
           $scope.txtname = fullname;  
           $scope.txtusername = username;  
           $scope.btnName = "Update";  
      }  
      $scope.deleteData = function(id){  
           if(confirm("Are you sure you want to delete this data?"))  
           {  
                $http.post("delete.php", {'id':id})  
                .success(function(data){  
                     alert(data);  
                     $scope.displayData();  
                });  
           }  
           else  
           {  
                return false;  
           }  
      }  
 });  
</script>  		   
</body>  
</html>  
db.php
//db.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");
?>
list.php
//list.php
<?php  
include('db.php');

$query = "SELECT * FROM tbl_user ORDER BY userid DESC";
$statement = $connect->prepare($query);
if($statement->execute())
{
  while($row = $statement->fetch(PDO::FETCH_ASSOC))
  {
    $data[] = $row;
  }
  echo json_encode($data);
}

?>
insert_update.php
//insert_update.php
<?php
include('db.php');

$message = '';

$form_data = json_decode(file_get_contents("php://input"));
 
if ($form_data->txtid == '0') {

	$data = array(
	 ':txtname'  => $form_data->txtname,
	 ':txtusername'  => $form_data->txtusername
	); 
		
	$query = "
	 INSERT INTO tbl_user 
	 (fullname, username) VALUES 
	 (:txtname, :txtusername)
	";

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

	if($statement->execute($data))
	{
	 $message = 'Data Inserted';
	}else {
	 $message = 'Error';	
	}	
}else {
	
	$data = array(
	 ':txtname'  => $form_data->txtname,
	 ':txtusername'  => $form_data->txtusername,
	 ':txtid'  => $form_data->txtid
	); 
	
	$query = "
	 UPDATE tbl_user 
	 SET fullname = :txtname, username = :txtusername 
	 WHERE userid = :txtid
	";

	$statement = $connect->prepare($query);
	if($statement->execute($data))
	{
	 $message = 'Data Edited';
	}
}	
echo $message; 
?>
delete.php
//delete.php
<?php
include('db.php');

$message = '';

$data = json_decode(file_get_contents("php://input"));
$id = $data->id;  
$query = "DELETE FROM tbl_user WHERE userid='$id'";  

$statement = $connect->prepare($query);
if($statement->execute())
{
 $message = 'Data Deleted';
}else{
  $message = 'Error';	
}	
echo $message;
?>

AngularJS Login with PHP MySQLi

AngularJS Login with PHP MySQLi

This tutorial used CDN for Bootstrap, Angular JS and Angular Route

CREATE TABLE `tbl_user` (
  `userid` int(11) NOT NULL,
  `fullname` varchar(50) NOT NULL,
  `username` varchar(100) NOT NULL,
  `email` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `tbl_user` (`userid`, `fullname`, `username`, `email`, `password`) VALUES
(1, 'cairocoder Ednalan', 'cairocoders', '', '123456'),
(2, 'tutorial101', 'tutorial101', '', '123456');

ALTER TABLE `tbl_user`
  ADD PRIMARY KEY (`userid`);

ALTER TABLE `tbl_user`
  MODIFY `userid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
index.html
//index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>AngularJS Login with PHP MySQLi</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
  <h1 class="page-header text-center">AngularJS Login with PHP MySQLi</h1>
  <div ng-view></div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js"></script>
<script src="js/angular.js"></script>
<script src="js/controllers/loginCtrl.js"></script>
<script src="js/services/loginService.js"></script>
</body>
</html>
login.html
//login.html
<div class="col-md-4 col-md-offset-4">
    <div class="login-panel panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title"><span class="glyphicon glyphicon-lock"></span> Login
            </h3>
        </div>
    	<div class="panel-body">
        	<form role="form" name="logform">
            	<fieldset> sdfsdfsf
                	<div class="form-group">
                    	<input class="form-control" placeholder="Username" type="text" autofocus ng-model="user.username" required>
                	</div>
                	<div class="form-group">
                    	<input class="form-control" placeholder="Password" type="password" ng-model="user.password" required>
                	</div>
                	<button type="button" id="loginbutton" class="btn btn-lg btn-primary btn-block" ng-disabled="logform.$invalid" ng-click="login(user)"><span class="glyphicon glyphicon-log-in"></span> <span id="logtext">Login</span></button>
            	</fieldset>
        	</form>
    	</div>
    </div>

    <div class="alert alert-danger text-center" ng-show="errorLogin">
        <button type="button" class="close" ng-click="clearMsg()"><span aria-hidden="true">×</span></button>
        {{ errorMsg }}
    </div>

    <div class="alert alert-success text-center" ng-show="successLogin">
        <button type="button" class="close" ng-click="clearMsg()"><span aria-hidden="true">×</span></button>
        {{ successMsg }}
    </div>
</div>
angular.js
//angular.js
var app = angular.module('app', ['ngRoute']); //Routing - ngRoute module helps your application to become a Single Page Application.

app.config(function($routeProvider){
	$routeProvider
	.when('/', {
		templateUrl: 'login.html',
		controller: 'loginCtrl'
	})
	.when('/home', {
		templateUrl: 'home.html'
	})
	.otherwise({
		redirectTo: '/'
	});
});
js/services/loginService.js
//js/services/loginService.js
'use strict';

app.factory('loginService', function($http){
	return{
		login: function(user, $scope){
			var validate = $http.post('login.php', user);
			validate.then(function(response){
				if(response.data.error == true){
					$scope.successLogin = false;
					$scope.errorLogin = true;
					$scope.errorMsg = response.data.message;
				}
				else{
					$scope.errorLogin = false;
					$scope.successLogin = true;
					$scope.successMsg = response.data.message;
                    setTimeout(function(){
						window.location.href="http://localhost/devtest/angularjs/angularlogin/#/home";
					},2000);
				}
			});
		}
	}
});
js/controller/loginCtrl.js
//js/controller/loginCtrl.js
'use strict';

app.controller('loginCtrl', function($scope, loginService){
	$scope.errorLogin = false;
	$scope.successLogin = false;

	$scope.login = function(user){
		loginService.login(user, $scope);
	}

	$scope.clearMsg = function(){
		$scope.errorLogin = false;
		$scope.successLogin = false;
	}
});
login.php
//login.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$out = array('error' => false);

$user = json_decode(file_get_contents('php://input'));

$username = $user->username;
$password = $user->password;

$sql = "SELECT * FROM tbl_user WHERE username='$username' AND password='$password'";
$query = $conn->query($sql);

if($query->num_rows>0){
	$out['message'] = 'Login Successful';
}
else{
	$out['error'] = true;
	$out['message'] = 'Invalid Login';
}

echo json_encode($out);
?>

Friday, September 4, 2015

AngularJS Forms Custom Model Update Triggers

AngularJS Forms Custom Model Update Triggers

The novalidate attribute

1. updateOn option of the ng-model-options directive. The model value updates when the focus is lost.
2. debounce option delays the model update. update the model after 250 milliseconds
3. updateOn and debounce option. Setting the debounce value of blur event to ‘0’ indicates that the model trigger immediate update when it is out of focus.
<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>AngularJS Custom Model Update</title>  
 </head>
 <body ng-app="formApp">
  <div ng-controller="FormController">
   <form novalidate>
    Name : <input type="text" ng-model="employee.name" ng-model-options="{updateOn:'blur'}"/></br>
    Gender : <input type="text" ng-model="employee.gender" ng-model-options="{debounce:250}"/></br>
    E-mail : <input type="email" ng-model="employee.email" ng-model-options="{updateOn:'blur',debounce:{blur:0} }"/></br>
   </form>
     <p>Name : {{employee.name}}</p>
   <p>Gender : {{employee.gender}}</p>
   <p>Email : {{employee.email}}</p>
  </div>
  </div>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
 <script type="text/javascript">
  var app = angular.module('formApp', []);
  app.controller('FormController', function($scope) {
   $scope.employee = {};

  });
 </script>
</body>
</html>

AngularJS

AngularJS


AngularJS is a JavaScript framework. It can be added to an HTML page.

AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.

AngularJS is perfect for Single Page Applications (SPAs).

AngularJS is easy to learn.
https://angularjs.org/

Related Post