Category: Angular JS

facebook-auth-image
Angular JS

Facebook Authentication With Angular JS And Satellizer

hello there, today we are going to learn how can we do facebook authentication using angular js and Satellizer. before we begin the practical part let’s see what is Satellizer and how can we use it for Facebook authentication. what is satelizer? Satellizer is an end-to-end, token-based authentication module for AngularJS with built-in support for Google, Facebook, Linked In, and other social media, etc as well as Email and Password sign-in. Satellizer is simple to use. However, you are not limited to the sign-in options above, in fact, you can add any OAuth 1.0 or OAuth 2.0 provider bypassing provider-specific information in the app config block. you can learn more about satelizer here. satelizer installation and Requirements. in this tutorial, we are gonna use Satellizer through CDN.
<script src="https://cdn.jsdelivr.net/satellizer/0.15.5/satellizer.min.js"></script>
another installation process is also there for the node JS or if you want to install it in the browser you can visit here. also, you can check the requirements for mobile apps there. so now we are going to do Facebook authentication with angular js and Satellizer, first of all, we are going to do the front-end part then we are going to do scripting. so let’s create an index page with a Facebook login button then we will do authentication. Let’s create front-end For the tutorial

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://cdn.jsdelivr.net/satellizer/0.15.5/satellizer.min.js"></script>

<style>
body {
  font-family: Arial, Helvetica, sans-serif;
}

* {
  box-sizing: border-box;
}

/* style the container */
.container {
  position: relative;
  border-radius: 5px;
  background-color: #f2f2f2;
  padding: 20px 0 30px 0;
  width: 800px;
  float: right;
  height: 400px;
  top: 100px;
} 

/* style inputs and link buttons */
input,
.btn {
  width: 100%;
  padding: 12px;
  border: none;
  border-radius: 4px;
  margin: 5px 0;
  opacity: 0.85;
  display: inline-block;
  font-size: 17px;
  line-height: 20px;
  text-decoration: none; /* remove underline from anchors */
}

input:hover,
.btn:hover {
  opacity: 1;
}

/* add appropriate colors to fb, twitter and google buttons */
.fb {
  background-color: #3B5998;
  color: white;
}

.twitter {
  background-color: #55ACEE;
  color: white;
}

.google {
  background-color: #dd4b39;
  color: white;
}

/* style the submit button */
input[type=submit] {
  background-color: #04AA6D;
  color: white;
  cursor: pointer;
}

input[type=submit]:hover {
  background-color: #45a049;
}

/* Two-column layout */
.col {
  float: left;
  width: 50%;
  margin: auto;
  padding: 0 50px;
  margin-top: 6px;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

/* vertical line */
.vl {
  position: absolute;
  left: 50%;
  transform: translate(-50%);
  border: 2px solid #ddd;
  height: 275px;

}

/* text inside the vertical line */
.vl-innertext {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: #f1f1f1;
  border: 1px solid #ccc;
  border-radius: 50%;
  padding: 8px 10px; 
}

/* hide some text on medium and large screens */
.hide-md-lg {
  display: none;
}

/* bottom container */
.bottom-container {
  text-align: center;
  background-color: #666;
  border-radius: 0px 0px 4px 4px;
}

/* Responsive layout - when the screen is less than 650px wide, make the two columns stack on top of each other instead of next to each other */
@media screen and (max-width: 650px) {
  .col {
    width: 100%;
    margin-top: 0;
  }
  /* hide the vertical line */
  .vl {
    display: none;
  }
  /* show the hidden text on small screens */
  .hide-md-lg {
    display: block;
    text-align: center;
  }
}
</style>
</head>
<body ng-app="myApp" ng-controller="LoginCtrl">
<div class="container">
  <form method="post">
    <div class="row">
      <h2 style="text-align:center">Login with Social Media or Manually</h2>
      <div class="vl">
        <span class="vl-innertext">or</span>
      </div>

      <div class="col">
        <button class="fb btn"  ng-click="authenticate('facebook')">
          <i class="fa fa-facebook fa-fw"></i> Login with Facebook
         </button>
        <a href="#" class="twitter btn">
          <i class="fa fa-twitter fa-fw"></i> Login with Twitter
        </a>
        <a href="#" class="google btn"><i class="fa fa-google fa-fw">
          </i> Login with Google+
        </a>
      </div>
    </form>
      <div class="col">
        <div class="hide-md-lg">
          <p>Or sign in manually:</p>
        </div>
        <form method="post">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <input type="submit" value="Login">
        </form>
      </div>
    </div>
  </form>
</div>
<script type="text/javascript" src="app.js"></script>

</body>
</html>

this is the front-end part of the UI. now when the user clicks sign in with Facebook then there should be a popup for authentication so now let’s create this first. so if you want to make a Facebook authentication then you must have an account on the Facebook developer console website. so first create an account in the Facebook developer console then create a new application fill the all the forms and required fields. then you have to go to your application and click on the library section where you can find the Facebook login library and you have to install your app in code using application code. Let’s create a script for authentication. there is all the script available here. you just have to put your application code then see if it works or not but here we have created a script like this, which is only for Facebook authentication. the script which we have written is in angular JS so must have a knowledge of angular js, so you need to learn angular js, some basic funda of angular js is must required.
var MyApp = angular.module('myApp', ['satellizer'])
  MyApp.config(function($authProvider) {
    var AuthUrl = 'http://localhost/facebookAuth/index.php';
    $authProvider.facebook({
    clientId: 'your application id',
    name: 'facebook',
    url: AuthUrl,
    authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog/oauth',
    requiredUrlParams: ['display', 'scope'],
    scope: ['email'],
    scopeDelimiter: ',',
    display: 'popup',
    oauthType: '2.0',
    popupOptions: { width: 580, height: 400 }
    });
  });
  MyApp.controller('LoginCtrl', function($scope, $auth) 
  {
    $scope.authenticate = function(provider) {
      $auth.authenticate(provider)
        .then(function (response){
        console.log("connected successfully");       
    };
});

once your account is verified you can do what you want to do after authentication. that’s it, for now, check our previous blogs here.
send OTP using angular js and php
Angular JS

How To Send OTP Using Angular JS And PHP?

hello there, today we are going to discuss how can we send OTP using angular js and PHP? so in this tutorial, we need to understand some advanced topics of PHP, and also How API call in PHP? in this tutorial we will use API for sending the message, which is free to use. so let’s get started. which service we will use for send OTP using angular js and php? so in this tutorial, we gonna use the fast2sms service which provides 50 free credits for send SMS. this service actually provides us bulk SMS service but will use this service as OTP verification. if you also want to use this service then please visit this link. so we know that we are going to use the free2sms service but how do we donna calls the API this is the main part of this tutorial, so we get a link from the fast2sms service but we need to call that service so we are gonna use cURL for this operation. What is cURL? curl is used in command lines or scripts to transfer data. curl is also used in cars, television sets, routers, printers, audio equipment, mobile phones, tablets, set-top boxes, media players and is the Internet transfer engine for thousands of software applications in over ten billion installations. what cURL supports? DICT, FILE, FTP, FTPS, GOPHER, GOPHERS, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, MQTT, POP3, POP3S, RTMP, RTMPS, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET and TFTP. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, HTTP/2, HTTP/3, cookies, user+password authentication (Basic, Plain, Digest, CRAM-MD5, SCRAM-SHA, NTLM, Negotiate and Kerberos), file transfer resume, proxy tunneling and more. Let’s Move to the front-end side of this tutorial. so in the front-end, we will use HTML, CSS, Bootstrap, and jquery. so in this tutorial, we will use some jquery functions too, so it makes our page much creative. so let’s create a user form and go through it.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>OTP Verification Using Angular JS And PHP</title>
  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
  <style type="text/css">
  	input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
  </style>
</head>
<body>
<div class="container-fluid" ng-app="OTPApp" ng-controller="OTPC">
	<div class="row">
		<div class="col-md-12">
			<h1 class="text-center">OTP Verification Using Angular JS AND PHP</h1>
			<div class="d-flex justify-content-center">

				<div class="card" style="border-radius: 20px;overflow: hidden;">
					<div id="msg"> </div>
					<div class="card-header">
						<h4 class="text-info">Please Verify Your Mobile Number</h4>
					</div>
					<div class="card-body">
					<div id="sendotp">
						<form>
							<label>Enter Your Mobile Number</label>
							<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"type = "number"maxlength = "10"
 							class="form-control" placeholder="please enter your mobile number here" id="mobile" ng-model="mobile" required/>
						</form>
					</div>
						<div id="verify">
							<form>
								<label>Enter OTP</label>
								<input type="number" oninput="javascript: if(this.value.length > this.maxLength) this.value=this.value.slice(0,this.maxLength);" maxlength="6" class="form-control" placeholder="please enter otp here" ng-model="otp">
							</form>
						</div>
					</div>
					<div class="d-flex justify-content-end card-footer">
						<button class="btn btn-primary" id="sendOtp" ng-click="sendOTP()">Send OTP</button>
						<button class="btn btn-success" id="verifyOTP" ng-click="verifyOTP()">Verify OTP</button>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
  <!-- Bootstrap core JavaScript -->
  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
this is the front-end but we need to apply some jquery here let’s generate it.
  	$(document).ready(function() {
  		$("#verify").hide();
  		$("#verifyOTP").hide();
  		$("#sendOtp").attr('disabled','disabled');
  		$("#mobile").keyup(function() {
  			var number = $(this).val();
  			if(number.length == 10){
  				$("#sendOtp").removeAttr('disabled','disabled');
  			}else{
  				$("#sendOtp").attr('disabled','disabled');
  			}
  		});
  	});
all the javascript or jquery code provide here you have to use inside the script tag. so you can call it properly. after complete these steps, your output should look like this. we have completed our front-end here now let’s go through the back-end of this tutorial. Let’s Move to the Back-end of the Send OTP Using Angular Js And PHP. so we completed the front-end so now we have to create a backend of the tutorial. so let’s create ajax for the calling API.
var app = angular.module('OTPApp',[]);
  	app.controller('OTPC',function($scope,$http){
  		$scope.sendOTP = function(){
  			$http.post('api/sendOTP.php',{'mobile_number':$scope.mobile,'submitFor':'submit_otp'}).then(function(res){
  				$("#msg").append(res.data);
  				$("#verify").show();
  				$("#verifyOTP").show();
  				$("#sendotp").hide();
  				$("#sendOtp").hide();
  			});
  		}
  		$scope.verifyOTP = function(){
  			$http.post('api/sendOTP.php',{'otp':$scope.otp,'submitFor':'verify_otp'}).then(function(res){
  				if(res.data['code']==200){
	  				$("#msg").append(res.data['info']);
  					$("#verify").hide();
  					$("#verifyOTP").hide();
  					$("#sendotp").show();
  					$("#sendOtp").show();
  				}else{
  					$("#msg").append(res.data['info']);
  				}
  			});
  		}
  	});
so we completed the front-side and also we completed the API call for sending SMS using angular js and PHP. now only one thing remaining that is the main part of this tutorial sending SMS API and how to use it.so we will use the API which is provided by the fast2sms, you can find it under the dashboard section inside the dev-API page where you can find your API key.so let’s create an API for send SMS.
<?php

error_reporting(0);
$data =json_decode(file_get_contents("php://input"),true);
$mobile = mysql_real_escape_string($data['mobile_number']);
$uotp = mysql_real_escape_string($data['otp']);
$ch = mysql_real_escape_string($data['submitFor']);
switch ($ch) {
	case 'submit_otp':
		$num = $mobile;			
		$otp = rand(100000,999999);
		setcookie('otp',$otp);
		$key ="your key";
		$route = "get from your dashboard";
		$senderid = "get from your dashboard";
		$message = "Hello your varification OTP is $otp";
		$language = "english";
		$flash=0;
		$url = "dev/bulkV2?".
		"authorization=".$key."&".
		"route=".$route."&".
		"sender_id=".$senderid."&".
		"message=".urlencode($message)."&".
		"language=".$language."&".
		"flash=".$flash."&".
		"numbers=".urlencode($num);
		$curl = curl_init();
		curl_setopt_array($curl, array(
		CURLOPT_URL => $url,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_ENCODING => "",
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_TIMEOUT => 30,
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_CUSTOMREQUEST => "GET",
		CURLOPT_POSTFIELDS => "",
		CURLOPT_HTTPHEADER => array(
		    "content-type: application/x-www-form-urlencoded"
		  ),
	));
	$response = curl_exec($curl);
	$err = curl_error($curl);
	curl_close($curl);
	if ($err) {
	  echo "cURL Error #:" . $err;
	} else {
		// echo $response;
	  echo '<div class="alert alert-success alert-dismissible fade show" role="alert">
    <strong>Success !</strong> your OTP has been sent.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>'; 
	}
	break;
	case 'verify_otp':
		$user_otp = $uotp;
		$verify_otp = $_COOKIE['otp'];
		if($verify_otp == $user_otp){
			$response =array('res'=> '<div class="alert alert-success alert-dismissible fade show" role="alert">
    <strong>Success !</strong> your OTP successfully verified.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>','code'=>200);
    setcookie("otp", "", time() - 3600);
echo json_encode($response);
		}else{
			$response =array('info'=>'<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <strong>Failed !</strong> Please check your OTP.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>',code=>201);
    echo json_encode($response);

		}
		break;
}
?>
so now everything is done now you have to just run this file and check that you receive an SMS or not, if not then let us know in our comment section, and also if you want to learn that how to send E-mail using angular JS and PHP then please visit our this blog.
3
send email using phpmailer
Angular JS

How To Send Email Using PHPMailer And Angular JS

hello there, in this tutorial we will discuss send Email Using phpmailer and Angular JS. So we need to go through the basics of phpmailer and how to use the service of phpmailer? so let’s start with the basics. what is PHPMailer ? Many PHP developers need to send emails from their code. The only PHP function that supports this directly is mail(). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments. Formatting email correctly is surprisingly difficult. There are myriad overlapping (and conflicting) standards, requiring tight adherence to horribly complicated formatting and encoding rules – the vast majority of code that you’ll find online that uses the mail() function directly is just plain wrong, if not unsafe! The PHP mail() function usually sends via a local mail server, typically fronted by a sendmail binary on Linux, BSD, and macOS platforms, however, Windows usually doesn’t include a local mail server; PHPMailer’s integrated SMTP client allows email sending on all platforms without needing a local mail server. Be aware though, that the function should be avoided when possible; it’s both faster and safer to use SMTP to localhost. Features Of PHPMailer. Probably the world’s most popular code for sending email from PHP!Used by many open-source projects: WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla! and many moreIntegrated SMTP support – send without a local mail serverSend emails with multiple To, CC, BCC and Reply-to addressesMultipart/alternative emails for mail clients that do not read HTML emailSupport for UTF-8 content and 8bit, base64, binary, and quoted-printable encodingsSMTP authentication with LOGIN, PLAIN, CRAM-MD5, and XOAUTH2 mechanisms over SMTPS and SMTP+STARTTLS transportsValidates email addresses automaticallyProtects against header injection attacks if you want to know more about it please visit this link. How To Send Email Using PHPMailer? so in this tutorial, we gonna use phpmailer as we use in PHP and we will use the ajax method in this tutorial so if you don’t know how to use ajax in angular js, please learn from our previous tutorial which you can visit directly from here. Send Email Using PHPMailer And Angular JS. so here we will discuss that how to integrate PHPMailer with and how to send Emails using phpmailer and angular js. so here we need to create one simple form using HTML, CSS, or bootstrap. here we created a form using bootstrap so let’s check out that form.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>Send Email Using Angular JS</title>
  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
  <div class="container-fluid" ng-app="mailApp" ng-controller="mailC">
      <div class="row">
  	 <div class="col-md-12">
            <div class="d-flex justify-content-center col-md-12">
               <form name="Form1">
  		 <h1>Send Email Using Angular JS and PHPMailer</h1>
  		<div id="msg"></div>
  		<label>Enter Reciver Email Address</label>
  		<input type="email" name="rEmail" ng-model="receiver_email" class="form-control" required>
  		<label>Subject</label>
                <input type="text" ng-model="subject" class="form-control">
                <label>Enter Message</label>
  		<textarea class="form-control" cols="12" rows="5" ng-model="message"></textarea>
               <div class="d-flex justify-content-center">
  	       <button class="btn btn-secondary mt-3" ng-click="sendEmail()">Send Email</button>
            <div>
  	</form>
     </div>
  </div>
 </div>
</div>	
  <!-- Bootstrap core JavaScript -->
  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
here is the output for the above code. here we provided an email address, subject, and message you have to fill this form and submit this form here we see how to submit this form using angular JS. setting up angular js for submitting form.
<script>
    var app = angular.module('mailApp', []);
    app.controller('mailC',function($scope,$http){
    $scope.sendEmail = function(){
    $http.post('api/sendEmail.php',{'receiverEmail':$scope.receiver_email,'subject':$scope.subject,'message':$scope.message}).then(function(res){
          $scope.reciver_email = "";
          $scope.subject = "";
          $scope.message = "";
          $("#msg").append(res.data);
        });
      }
    });
  </script>
so you can see that we did call the sendEmail.php file and we used ajax for the send email using phpmailer. we completed the front-end of this tutorial now we have to move to the backend.
<?php
error_reporting(0);
$data = json_decode(file_get_contents("php://input"),true);
$receiverEmail = $data['receiverEmail'];
$subject = $data['subject'];
$message = $data['message'];
	use PHPMailer\PHPMailer\PHPMailer;
  	use PHPMailer\PHPMailer\Exception;
    
  	require '../vendor/autoload.php';
    
  	  $mail = new PHPMailer(true);
    
      $mail->isSMTP();                                            
      $mail->Host       = 'smtp.gmail.com;';                    
      $mail->SMTPAuth   = true;                             
      $mail->Username   = 'your email address';                 
      $mail->Password   = 'your email password';                        
      $mail->SMTPSecure = 'tls';                              
      $mail->Port       = 587;  
      $mail->setFrom('your Email address', 'your nick name for email');           
      $mail->addAddress($reciverEmail);
      $mail->isHTML(true);                                  
      $mail->Subject = $subject;
      $mail->Body    = $message;
      $mail->AltBody = 'Body in plain text for non-HTML mail clients';
      try{
      if($mail->send()){
        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">
    <strong>Success !</strong> your Email is sent.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>';
      }
  } catch (Exception $e) {
      echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <strong>Success !</strong> your Email is Not sent.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>';
  }
  
?>
so here it is completed with the front-end as well as the backend if you want to learn how to send SMS using PHP then visit this link.
crud operation with angular js
Angular JS

CRUD Operation Using Angular JS, AJAX, AND PHP.

Hello, there in this blog we are discussing angular JS. we need to understand what is angular JS? how actually it works with PHP? How can we use ajax in angular js with crud operation With Angular JS PHP and AJAX? What is Angular JS? Angular JS is developed And mainly by google’s angular Team. AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML’s syntax to express your application’s components clearly and succinctly. AngularJS’s data binding and dependency injection eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it an ideal partner with any server technology. if you want to know more about angular js visit this link. Why we use angular JS? Angular projects offer a great way to build single-page client applications by implementing HTML and Typescript functionalities. so here are some steps to code an angular js application. The first Steps involes that you must have knowledge about HTML, CSS, and Typescript. note typescript is not mendatory but you must know write code of HTML And CSS is required.you must have basic knowledge about javascript. because at the end you have to do scripting your application.in angular js navigation between different views is defined by service called route so your page will be same but your contant will be change as your request.angular js provide synchronization or data-binding occurs between your modal and view components, this offerning a reactive user experience. Therefore, the building blocks of the Angular workspace are fit for designing impressive Single Page Applications (SPAs). angular JS first hello world application using HTML and Angular JS.
<html>
<head>
<title>Hello World Using Angular JS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-init="hello='Hello World!'">
<p> {{ hello }} </p>
</div>
</body>
</html>
Here is the output for this practical, so in this tutorial, we are not gonna through the basics of angular js if you want to learn more about angular js then visit this website. How HTML Forms data binding with Angular JS and How we use form Data for CRUD Operation Using Angular JS AND PHP? so in this section, we will learn about how we get data from the form in angular JS and how we will use that data for crud operation using angular js and PHP. How To Bind Data From The Form In Angular JS? so here is the sample code for bind data from the form in angular JS.
<!DOCTYPE html>
<html>
<head>
<title>Data Binding in Angular JS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<div ng-app="">
Name: <input ng-model="name">
<h1>You entered: {{name}}</h1>
</div>
</body>
</html>
here is the output for this practical. so in angular JS, we use ng-modal to bind HTML data with angular JS application. if you want to know more about angular JS modal then visit this website. How to do CRUD Operation Using Angular JS? so till now, we learn what is angular js and how to bind HTML data with angular js Applications. we need to generate our project structure for this practical. we will do all the operation step by step so you can easily understand and implement by your self. File structure for crud operation using angular JS. so in this tutorial, we gonna follow this file structure, in the API folder, you can see that different files are there which specifies why and what is the use of that files. so as a name suggest delete.php file will use for deletion and the insert.php file use for register user data and update.php will update user data and show.php file list all user data. in the config file, there is one file that is used for database connections, and using that file we can perform all the operations. At last main file is index.php where we perform all the operations. in that file, we use bootstrap for designing and all the files of bootstrap and angular js are called via CDN. let’s create index.html file.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>Angular JS CRUD AJAX</title>
  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<div class="container-fluid" ng-app="crudApp" ng-controller="crudController" ng-init="showData()">
	<div class="modal fade" id="modal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Insert Record</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form class="form-group" name="formsubmit"> 
        	<label for="">Name</label>
        	<input type="text" name="text" class="form-control" placeholder="Enter your Name Here" required ng-model="name">
        	<label for="">Email</label>
        	<input type="text" name="email" class="form-control" placeholder="Enter your Email Address Here" required ng-model="email">
        	<label>Phone</label>
        	<input type="number" name="phone" class="form-control" placeholder="Enter your Mobile number here" required ng-model="phone">
        	<input type="hidden" ng-model="userId">
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" ng-click="submitData()" data-dismiss="modal">Submit Data</button>
      </div>
    </div>
  </div>
</div>
<div class="modal fade" id="update" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Update Record</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form class="form-group"> 
        	<label for="">Name</label>
        	<input type="text" name="text" class="form-control" placeholder="Enter your Name Here" required ng-model="name">
        	<label for="">Email</label>
        	<input type="text" name="email" class="form-control" placeholder="Enter your Email Address Here" required ng-model="email">
        	<label>Phone</label>
        	<input type="number" name="phone" class="form-control" placeholder="Enter your Mobile number here" required ng-model="phone">
        	<input type="hidden" ng-model="userId">
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" ng-click="update()" data-dismiss="modal">Update Data</button>
      </div>
    </div>
  </div>
</div>
	<h2 class="text-center text-info">CRUD Operation With Angular JS And PHP</h2>

<div id="alertMessage">
	
</div>
		<div class="d-flex justify-content-end">
			<button class="btn btn-success mr-3" data-toggle="modal" data-target="#modal1">Add</button>
		</div>
		<div class="table-responsive">
			<table class="table table-striped mt-3">
				<thead>
					<tr>
						<th>
							Name
						</th>
						<th>
							Email
						</th>
						<th>
							Phone
						</th>
						<th>
							UPDATE
						</th>
						<th>
							DELETE
						</th>
					</tr>
				</thead>
				<tbody  ng-repeat="data in dataset">
					<td>{{ data.name }}</td>
					<td>{{ data.email }}</td>
					<td>{{ data.phone }}</td>
					<td><button class="btn btn-warning text-white" ng-click="updateData(data.id)" data-toggle="modal" data-target="#update">UPDATE</button></td>
					<td><button class="btn btn-danger" ng-click="deleteData(data.id)">DELETE</button></td>
				</tbody>
			</table>
		</div>
</div>
  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
this file will look like this, once you click add button you will see a modal like this. so in this tutorial, we used only three records for user registration, you can use anything you want. going through config file and database connectivity. show.php file
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_db_name";
try {
$dbconn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
lets create code for show.php and insert.php file and call API using ajax in angular JS.
<?php
require_once '../config/db_config.php';
$query = "SELECT * FROM table_name ORDER BY id DESC";
$selectDataQuery = $dbconn->prepare($query);
$selectDataQuery->execute();
$rowsData = $selectDataQuery->rowCount();
if($rowsData > 0){
$fetchData = $selectDataQuery->fetchAll(PDO::FETCH_ASSOC);
}else{
	$fetchData = [];
}
echo json_encode($fetchData);
?>
so in the show.php file, we used simple PHP code where we can see that we used simple to fetch all data from the database and store it in one variable then we just passed encoded JSON as output. what happened when we call an API for this file and how it works let’s see, create ajax for show.php file and call it using ajax
<Script>

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

  	app.controller('crudController',function($scope,$http){
  		$scope.showData = function(){
  			$http.get('api/show.php').then(function (response){
        	$scope.dataset = response.data;
        });
     }    

so in the above code, we can see that we used angular js module and scope and controller so if you don’t know what this all thing then please complete the basics of angular js which is available here. so we set response data for the dataset variable and we used the ng-repeat angular js function which is used for pass array just like for loop in other languages. lets create insert.php file and ajax for insert data.
<?php
require_once('../config/db_config.php');
$data = json_decode(file_get_contents("php://input"),true);
$name = mysql_real_escape_string($data['name']);
$email = mysql_real_escape_string($data['email']);
$phone = mysql_real_escape_string($data['phone']);
$submitFor = mysql_real_escape_string($data['submitFor']);
$id = mysql_real_escape_string($data['id']);
if($submitFor == 'insertData'){
  $query = "INSERT INTO `table_name`(`name`, `email`, `phone`) VALUES ('$name','$email','$phone')";
  $insertQuery = $dbconn->prepare($query);
  if($insertQuery->execute()){
    echo '<div class="alert alert-success alert-dismissible fade show" role="alert">
    <strong>Success !</strong> your Data is submitted.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>';
  }else{
    echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <strong>Sorry !</strong> your Data submission is failed.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>';
  }  
}elseif ($submitFor == 'updateData') {
  $query = "UPDATE `table_name` SET `name`='$name',`email`='$email',`phone`='$phone' WHERE id=$id";
  $updateQuery = $dbconn->prepare($query);
  if($updateQuery->execute()){
    echo '<div class="alert alert-success alert-dismissible fade show" role="alert">
    <strong>Success !</strong> your Data updated.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>';
  }else{
    echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <strong>Failed !</strong> Failed to update Data.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>';
  }
}

?>
so in the above code, we can see that we used something which maybe you show the first time and it is the file_get_contents PHP function which is used to get data from API or retrieve data from form-data. when we are using the angular js ajax method then we pass the data in form-data which is you can see under the network tab. when we are passing data from angular js and it is passed in API as encoded JSON format so first of all we need to decode the data and then retrieve all data one by one. so if you notice that we used to submit for variable in which we check that is this form submit for update data or just insert data so we used the same file for doing both works for us.
$scope.submitData = function(){
      $http.post('api/insert.php',{'id':$scope.userId,'name':$scope.name,'email':$scope.email,'phone':$scope.phone,'submitFor':'insertData'}).then(function(res){
      	$("#alertMessage").append(res.data);
      	$scope.showData();
      });
     }
here is the AJAX call for the insert data from the Form. so here you can see that we passed different parameters in the ajax call which are id, name, email, phone, and submit for so all data will be passed in insert.php file as encoded JSON format and then we decode them and use them for our task. lets create update and delete functionality.
<?php
require_once '../config/db_config.php';
$udata = json_decode(file_get_contents("php://input"),true);
$id = $udata['id'];
$query = "SELECT * FROM table_name where id=$id";
$selectDataQuery = $dbconn->prepare($query);
$selectDataQuery->execute();
$rowsData = $selectDataQuery->rowCount();
if($rowsData > 0){
$fetchData = $selectDataQuery->fetchAll(PDO::FETCH_ASSOC);
	foreach ($fetchData as $data) {
		$userData['name'] = $data['name'];
		$userData['email'] = $data['email'];
		$userData['phone'] = $data['phone'];
	}
}else{
          $userData= [];
     }
echo json_encode($userData);
?>

so in the above code, we are using the show function but this time we don’t want to show all data we only want to show some particular user data so for this we used user_id so each time when the user clicks update function the update function is called and passed id to API.
$scope.updateData = function(id){
     	$http.post('api/update.php',{'id':id}).then(function(res){
     		$scope.name = res.data['name'];
     		$scope.email = res.data['email'];
     		$scope.phone = parseInt(res.data['phone']);
     		$scope.userId = id;
     	});
     }
so the above code sets the response data for the particular field. so after clicking the update button you can see this modal with user data when we click the update Data button this will again call insert.php file but submit for will update data so this time that will not create a new user that will update particular user data.
$scope.update = function(){
$http.post('api/insert.php',{'id':$scope.userId,'name':$scope.name,'email':$scope.email,'phone':$scope.phone,'submitFor':'updateData'}).then(function(res){
      	$("#alertMessage").append(res.data);
      	$scope.showData();
      });
     }

lets create delete functionality. so one of the easiest methods is to delete data from the database. so in this method, we just gonna use the id for the deletion. this is the easiest method so we don’t need to use too much complex code for this.
$scope.deleteData = function(id){
     	if(confirm('Are you sure ?')){
     		$http.post('api/delete.php',{'id':id}).then(function(res){
     			$("#alertMessage").append(res.data);
	      	$scope.showData();
	      });
     	}
     }
so here is the API code for the deletion operation.
<?php
require_once('../config/db_config.php');
$data = json_decode(file_get_contents("php://input"),true);
$id = $data['id'];
$deleteQuery = "DELETE FROM table_name where id = $id";
$deleteqry = $dbconn->prepare($deleteQuery);
if($deleteqry->execute()){
	echo '<div class="alert alert-success alert-dismissible fade show" role="alert">
    <strong>Success !</strong> your Data successfully deleted.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>';
}else{
	echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <strong>Failed !</strong> failed to delete data.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>';
}
?>
that’s it guys if you getting any errors let us know in the comment and learn vagrant for Symfony.
×