Você está na página 1de 3

baljeetsingh.

in

http://baljeetsingh.in/blog/angularjspostrequestphpcreatingloginform309/

AngularJSPOSTrequestwithPHP(Creatingloginform)
AftersearchingthroughmanyarticlesforhowtosendAngularJSPOSTdatatoPHP,thesolutionsifoundwerenotuptothepoint.So,idecidedtocreateasimpleloginformthatwill
POSTdatatoPHP&inthePHPfilewecanchecktheposteddataagainstthevaluesinourmysqldatabaseorwhateverdatabase,butiamcheckingtherequesteddataagainstthestatic
values&thenthePHPscriptreturntheresponsebacktotheclientside.
LiveDemo:http://baljeetsingh.in/ngPostAjax
Thereare3filesnamelyindex.html,app.js,login.php
Intheindex.html,thereisloginform
Intheapp.js,Angularmodule&controllerisdefined
Inthelogin.php,thevalidationisdone(currentlyagaintstaticvalues)

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf8"/>
<title>AngularJSPostdatawithPHP</title>
<linkrel="stylesheet"href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.24/angular.min.js">
src="app.js"type="text/javascript">
</head>
<body>
<divclass="container">
<h1>AngularJSajaxPOSTwithPHP</h1>
<divngapp='angularPostPHP'ngcontroller='loginCtrl'>
<inputclass="formcontrol"type="text"ngmodel="email"placeholder="EnterYourEmail"><br>
<inputclass="formcontrol"type="password"ngmodel="password"placeholder="EnterYourPassword"><br>
<buttonclass="btnbtnsuccess"ngclick="login()">Login</button><br>

17
18
19
20
21

<span>{{responseMessage}}</span>
</div>
</div>
</body>
</html>

app.js

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

varapp=angular.module('angularPostPHP',[])

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

$scope.login=function(){

varrequest=$http({
method:"post",
url:"login.php",
data:{
email:$scope.email,
password:$scope.password
},
headers:{'ContentType':'application/xwwwformurlencoded'}
})
/*SuccessfulHTTPpostrequestornot*/
request.success(function(data){
if(data=="1"){
$scope.responseMessage="SuccessfullyLoggedIn"
}
else{
$scope.responseMessage="UsernameorPasswordisincorrect"
}
})
}

26

})

login.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14

//checkusernameorpasswordfromdatabase
$postdata=file_get_contents("php://input")
$request=json_decode($postdata)
$email=$request>email
$password=$request>password
if($email=="one"&&$password=="one"){
echo"1"
}
else{
echo"0"
}
?>

Copythecontentstotheirrespectivefiles&thenrunindex.html.
RightUsername/PasswordCombination:one/one
Whenyoutypethisusername/passwordcombination,youwillgetsuccessfullyloggedin&whenwrongcombination,youwillgetUsernameorPasswordisincorrectasdescribedinthe
app.js.Whichisdonewiththeresponsefromthelogin.php.
Iflogin.phpreturn1thenwegetSuccessfullyLoggedinelsewegetUsernameorPasswordisincorrect.

2016AllRightsReserved.BaljeetSingh

Você também pode gostar