Here i will give you an overview on, how i implemented a Login / Register in my app. You can also refer to my complete project via GitHub.
If you find it difficult to follow, please go through my previous set of tutorials on Ionic Development:
How to design HTML5 app using Ionic Cordova : Part 2
How to build HTLM5 app using Ionic Cordova: Part 3
How to build HTML5 Shopping Cart app using Ionic Cordova : Part 4
How to build HTML5 Shopping Cart app using Ionic Cordova : Part 5
[wpi_designer_button text=’Download’ link=’https://github.com/arjunsk/FoodKart’ style_id=’48’ icon=’github’ target=’_blank’]
UPDATE (10-07-16):
Latest FoodKart V0.3 is released. Read the complete tutorial here.
LEVEL 2 [ Intermediate ] :-
SERVER SIDE:
LOGIN PHP
<?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); if(isset($_GET["e"]) && isset($_GET["p"]) ){ if( !empty($_GET["e"]) && !empty($_GET["p"]) ){ $conn = new mysqli("localhost", "username", "password", "database"); $username=$_GET["e"]; $password=$_GET["p"]; // To protect MySQL injection for Security purpose $username = stripslashes($username); $password = stripslashes($password); $username = $conn->real_escape_string($username); $password = $conn->real_escape_string($password); $password = md5($password); $query="SELECT u_name, u_id, u_phone, u_address, u_pincode FROM users where u_verified=1 and u_id like '".$username."' and u_password like '".$password."'"; $result = $conn->query($query); $outp = ""; if( $rs=$result->fetch_array(MYSQLI_ASSOC)) { if ($outp != "") {$outp .= ",";} $outp .= '{"u_name":"' . $rs["u_name"] . '",'; $outp .= '"u_id":"' . $rs["u_id"] . '",'; $outp .= '"u_phone":"' . $rs["u_phone"] . '",'; $outp .= '"u_address":"' . $rs["u_address"] . '",'; $outp .= '"u_pincode":"'. $rs["u_pincode"] . '"}'; } $outp ='{"records":'.$outp.'}'; $conn->close(); echo($outp); } } ?>
REGISTER PHP :
<?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); if(isset($_GET["n"]) && isset($_GET["un"])&& isset($_GET["ps"])&& isset($_GET["ph"])&& isset($_GET["add"])&& isset($_GET["pin"]) ){ if( !empty($_GET["n"]) && !empty($_GET["un"])&& !empty($_GET["ps"])&& !empty($_GET["ph"])&& !empty($_GET["add"])&& !empty($_GET["pin"]) ){ $conn = new mysqli("localhost", "usrname", "password", "database"); $name=$_GET["n"]; $username=$_GET["un"]; $password=$_GET["ps"]; $password=md5($password); $phone=$_GET["ph"]; $address=$_GET["add"]; $pincode=$_GET["pin"]; // To protect MySQL injection for Security purpose $name = stripslashes($name); $username = stripslashes($username); $password = stripslashes($password); $phone = stripslashes($phone); $address = stripslashes($address); $pincode = stripslashes($pincode); $name = mysql_real_escape_string($name); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $phone = mysql_real_escape_string($phone); $address = mysql_real_escape_string($address); $pincode = mysql_real_escape_string($pincode); $check="SELECT * FROM users WHERE u_id = '$username'"; $rs = mysqli_query($conn,$check); $data = mysqli_fetch_array($rs, MYSQLI_NUM); // check if the user already exists. if($data[0] > 1) { $outp='{"result":{"created": "0" , "exists": "1" }'; } else{ $sql = "INSERT INTO users VALUES ('$name', '$username', '$password', '$phone','$address' ,'$pincode',1 )"; if ($conn->query($sql) === TRUE) { $outp='{"result":{"created": "1", "exists": 0" }'; } } // created= 1 means the account is created. // exists =1 means the account already exists. echo $outp; $conn->close(); } } ?>
MYSQL DATABASE
-- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `u_name` varchar(300) NOT NULL, `u_id` varchar(300) NOT NULL, `u_password` varchar(300) NOT NULL, `u_phone` varchar(300) NOT NULL, `u_address` varchar(300) NOT NULL, `u_pincode` varchar(300) NOT NULL, `u_verified` tinyint(1) NOT NULL, PRIMARY KEY (`u_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CLIENT SIDE
[color-box ] LOGIN PAGE [/color-box]
1. templates\login.html [ LOGIN PAGE]
<ion-view title="Login"> <ion-content padding="'true'" class="has-header"> <form class="list" > <ion-list> <label class="item item-input"> <span class="input-label">Email</span> // here we create a user object and store email as its property <input ng-model="user.email" type="email" placeholder="" > </label> <label class="item item-input"> <span class="input-label">Password</span> // user object <input ng-model="user.password" type="password" placeholder=""> </label> </ion-list> <div class="spacer" style="height: 40px;"></div> // login() function is called <button class="button button-stable button-block " ng-click="login()" >Log in</button> // a link to register page <a href="#/page5" class="button button-positive button-clear button-block ">Or create an account</a> </form> </ion-content> </ion-view>
2 . js\controllers.js [ loginCtrl ]
.controller('loginCtrl', function($scope,$http,$ionicPopup,$state,$ionicHistory) { $scope.user = {}; //declares the object user $scope.login = function() { str="http://www.website.com/foodcart/server_side/user-details.php?e="+$scope.user.email+"&p="+$scope.user.password; $http.get(str) .success(function (response){ // if login request is Accepted // records is the 'server response array' variable name. $scope.user_details = response.records; // copy response values to user-details object. //stores the data in the session. if the user is logged in, then there is no need to show login again. sessionStorage.setItem('loggedin_name', $scope.user_details.u_name); sessionStorage.setItem('loggedin_id', $scope.user_details.u_id ); sessionStorage.setItem('loggedin_phone', $scope.user_details.u_phone); sessionStorage.setItem('loggedin_address', $scope.user_details.u_address); sessionStorage.setItem('loggedin_pincode', $scope.user_details.u_pincode); // remove the instance of login page, when user moves to profile page. // if you dont use it, you can get to login page, even if you are already logged in . $ionicHistory.nextViewOptions({ disableAnimate: true, disableBack: true }); //in my FoodKart App, it checks the page from where the user logs in. //if it is from the check out, then after login, the check out page will be shown. //else normal profile page will be shown lastView = $ionicHistory.backView(); if(lastView.stateId=="checkOut"){ $state.go('checkOut', {}, {location: "replace", reload: true}); } else{$state.go('profile', {}, {location: "replace", reload: true});} }).error(function() { //if login failed var alertPopup = $ionicPopup.alert({ title: 'Login failed!', template: 'Please check your credentials!' }); }); }; })
3 . js\routes.js [ ROUTING ]
You can also add extra checking to make sure that login page is not visible , after user logs in( even when back button is pressed .)
.state('login', { url: '/page4', templateUrl: 'templates/login.html', controller: 'loginCtrl', resolve:{ "check":function($location){ if(sessionStorage.getItem('loggedin_id')){ $location.path('/page9'); } else { $location.path('/page4'); } } } })
[color-box ] SIGN UP PAGE [/color-box]
1. templates\signup.html [ REGISTRATION PAGE]
<ion-view title="Signup"> <ion-content padding="'true'" scroll="false" class="has-header"> <form class="list"> <ion-list> <label class="item item-input"> <span class="input-label">Name</span> //Note: data object contains all the detials about the user registering. <input type="text" placeholder="" ng-model="data.name"> </label> <label class="item item-input"> <span class="input-label">Username</span> <input type="email" placeholder="" ng-model="data.username"> </label> <label class="item item-input"> <span class="input-label">Password</span> <input type="password" placeholder="" ng-model="data.password"> </label> <label class="item item-input"> <span class="input-label">Phone</span> <input type="number" placeholder="" ng-model="data.phone"> </label> </ion-list> <label class="item item-input"> <span class="input-label">Address</span> <input type="text" placeholder="" ng-model="data.address"> </label> <label class="item item-input"> <span class="input-label">Pincode</span> <input type="number" placeholder="" ng-model="data.pincode"> </label> //data object is passed to the signup() <button ng-click="signup(data)" class="button button-stable button-block ">Sign up</button> </form> </ion-content> </ion-view>
2 . js\controllers.js [ signupCtrl]
.controller('signupCtrl', function($scope,$http,$ionicPopup,$state,$ionicHistory) { $scope.signup=function(data){ var link = 'http://www.website.com/foodcart/server_side/signup.php'; //using http post as we are passing password. $http.post(link, {n : data.name, un : data.username, ps : data.password , ph: data.phone , add : data.address , pin : data.pincode }) .then(function (res){ //if a response is recieved from the server. $scope.response = res.data.result; //contains Register Result //Shows the respective popup and removes back link if($scope.response.created=="1"){ $scope.title="Account Created!"; $scope.template="Your account has been successfully created!"; //no back option $ionicHistory.nextViewOptions({ disableAnimate: true, disableBack: true }); // the user is redirected to login page after sign up $state.go('login', {}, {location: "replace", reload: true}); }else if($scope.response.exists=="1"){ $scope.title="Email Already exists"; $scope.template="Please click forgot password if necessary"; }else{ $scope.title="Failed"; $scope.template="Contact Our Technical Team"; } var alertPopup = $ionicPopup.alert({ title: $scope.title, template: $scope.template }); }); } })
[color-box ] PROFILE PAGE [/color-box]
1. templates\profile.html [ USER PROFILE PAGE]
<ion-view title="Profile"> <ion-content padding="'true'" class="has-header"> <ion-list> <ion-item class="item-divider">Detials</ion-item> <label class="item item-input"> <span class="input-label">Name</span> <textarea placeholder="" readonly> {{" "+loggedin_name}}</textarea> </label> <label class="item item-input"> <span class="input-label">Email</span> <textarea placeholder="" readonly>{{" "+loggedin_id}} </textarea> </label> <label class="item item-input"> <span class="input-label">Phone</span> <textarea placeholder="" readonly > {{" "+loggedin_phone}}</textarea> </label> <label class="item item-input"> <span class="input-label">Address</span> <textarea placeholder="" readonly > {{" "+loggedin_address}}</textarea> </label> <label class="item item-input"> <span class="input-label">Pincode</span> <textarea placeholder="" readonly > {{" "+loggedin_pincode}}</textarea> </label> <div class="button-bar"> <a href="#/page10" class="button button-stable button-block icon ion-android-alarm-clock"></a> <a href="#/page11" class="button button-stable button-block icon ion-edit"></a> <a href="#/page12" class="button button-stable button-block icon ion-android-favorite"></a> </div> <button ng-click="logout()" class="button button-balanced button-block icon-left ion-log-out">Logout</button> <a href="tel:+8877887788" class="button button-calm button-block icon-left ion-android-call">Call Us</a> </ion-list> </ion-content> </ion-view>
2 . js\controllers.js [ profileCtrl ]
.controller('profileCtrl', function($scope,$rootScope,$ionicHistory,$state) { // loads value from the loggin session $scope.loggedin_name= sessionStorage.getItem('loggedin_name'); $scope.loggedin_id= sessionStorage.getItem('loggedin_id'); $scope.loggedin_phone= sessionStorage.getItem('loggedin_phone'); $scope.loggedin_address= sessionStorage.getItem('loggedin_address'); $scope.loggedin_pincode= sessionStorage.getItem('loggedin_pincode'); //logout function $scope.logout=function(){ //delete all the sessions delete sessionStorage.loggedin_name; delete sessionStorage.loggedin_id; delete sessionStorage.loggedin_phone; delete sessionStorage.loggedin_address; delete sessionStorage.loggedin_pincode; // remove the profile page backlink after logout. $ionicHistory.nextViewOptions({ disableAnimate: true, disableBack: true }); // After logout you will be redirected to the menu page,with no backlink $state.go('menu', {}, {location: "replace", reload: true}); }; })
UPDATE: ( 31-07-2016)
Here is a video demo of setting up Ionic Cart!
Good job! thank you for tutorial.
Can you implement in next parts, a way to sent cart content to a PHP – Mysql record and mail sender on checkout?
thankyou!
LikeLike
Thank you 🙂
Ok,I will surely let you know when i implement them.
LikeLike
I saw some great featuers you are planning to implement in the future release. May i know is that going to be soon ? And how long .. Thank you so much
LikeLike
Hello Modev,
I am currently working on FoodKart V0.3. The project is almost ready to go.
This is backended with Firebase for real-time cart and order tracking.
I am planing to write an article soon. Just follow me on git for latest updates.
I will share some of the screenshots below.
LikeLike
Ok i will be waiting… Good luck
LikeLike
Here are some of the screenshots
LikeLike
You can basically create a php page, to accept post request.
Then validate the post data ( For some script hacks ) and
use mailto() function in php to send it in the form of a formatted mail.
LikeLike
Great app!! While setting up the sign up & login functionality, I tried to use it as a user and tried to signup and it keep showing the error “TypeError: Cannot read property ‘created’ of undefined
at controllers.js:186”. This line is in the signup controller in controller.js where it checks if the record was found in the db or not. Did you encounter this too? Any tips please?
LikeLike
I didn’t face such issues.
Have you checked your PHP version. Mine is PHP version 5.5.34.
LikeLike
Thank you Tony.
I didn’t face any issue there.
Have you checked your PHP version?
My PHP version is 5.5.34.
LikeLike
If the PHP version was the issue then the food-menu.php won’t have worked too. That works fine and gets the data from the db to the app showing the list in the app just fine. I thought that some variable declaration or dependency injection in the signup controller or something like that could be the issue. Though I am checking but if you could recheck the same since you wrote it. Thanks in advance
LikeLike
1.I think, the JSON is not outputted correctly.
This usually happens to me when i try to edit the PHP file within filezilla.
(Some small formatting errors, usually some single quote changes into some other chars etc ).
2. And most importantly, check if the DB connection is working fine.
3. Are you facing the same issue with this also : https://github.com/arjunsk/ionic-shopping-cart-2
LikeLike
1. I think the JSON output could be the issue here. I used Filezilla to upload the php (though I used FileZilla for the menu php file too). I will recheck this. Can I also send the file that is there at the server so that you can give it a cursory look for some minor glitch (like you suggested)?
2. DB connection is fine for sure because the app loads the menu list from the same db just before I go to signup page. Further, if the db connection is not right then the error would have been different, isn’t it?
3. I haven’t faced the issue with other components yet. It worked fine.
Thanks again
LikeLike
Please email your server file at arjunsk15@gmail.com
LikeLike
Ya… there is an issue in the login page.
Now $ionicHistory does not support stateId. So i commented out the stateId part.
https://github.com/arjunsk/ionic-shopping-cart-2/commit/49448efde755ae82cfa5e737c2a7e659e832eea0
Current, I am working on FoodKart V0.3 which is based on Firebase backend. I app is completely redesigned and almost bug free.
Will be soon writing an article on it.
LikeLike
same problem…. can you fix it?
LikeLike
Once i click on login button on my device it does not let me in, and I need to go to homepage then again go backto user tab and in the profile page it shows undefined, I have uploaded the files on the live server, Please help
LikeLike
Have you added the following, in the success event of login() function?
$state.go(‘profile’, {}, {location: “replace”, reload: true});}
Also check it on this project: https://github.com/arjunsk/ionic-shopping-cart-2
LikeLike
Yes it is $state.go(‘profile’, {}, {location: “replace”, reload: true});}
LikeLike
you can do it? — fix undefined?
LikeLike
the live server is baskettechnologies.in/app/
LikeLike
Is this the app you are talking? I don’t find anything else there !
https://play.google.com/store/apps/details?id=com.thelaundryapp&hl=en
LikeLike
Can you share a private repo of your project, so that i could see the source code ?
LikeLike
I am discussion your food cart app, it gives me undefined in sql in resources tab, once i try to login.
I am referring to your login/register tutorial => http://www.arjunsk.com/html5/how-to-setup-loginregister-using-ionic-cordova-part-5
Where login does not work
LikeLike
Ok.. can you please confirm the following?
1. Have you checked controller.js
https://github.com/arjunsk/ionic-shopping-cart-2/blob/master/public_html/js/controllers.js#L162
2. Are you using the updated (signup.php)
https://github.com/arjunsk/ionic-shopping-cart-2/blob/master/server_side/signup.php
Your APP URL : http://baskettechnologies.in/app/
Automatically redirects to
http://baskettechnologies.in/app-ek-aur-charge-itna-kamm/
I wanted to see the console logs for troubleshooting.
LikeLike
Yes I downloaded the sample from your repo, and tested it.
It shows undefined once i login.
I have checked both the controller.js and signup.php
LikeLike
Can you add me in hangouts. This issue could be resolved via chat.
LikeLike
Sure, whats your ID ?
LikeLike
arjunsk15
LikeLike
Please send me a test at webmaster@ovibrands.com, Can’t find you
LikeLike
this is where i have kept the server files => baskettechnologies.in/app/food_menu.php and not referring to any other app
LikeLike
Check Screenshot https://uploads.disquscdn.com/images/3440760043f3483c572e07a5ce971f25d3914e6defa8f4fb6b7fa6e783b31e19.png
LikeLike
Latest Login, Register :
http://www.arjunsk.com/html5/ionic-loginsignup-using-firebase/
LikeLike
hello, when you run the app displays the items , but when I put signup in console gives me this error: ionic.bundle.js : 21162 TypeError : Can not read property ‘created ‘ of undefined
at controllers.js : 188
Even so , enter the data to the db correctly , and when I login with the data shows me all fields as undefined .
I use the updated signup.php
LikeLike
This issue was fixed in the FoodKart V0.2 . https://github.com/arjunsk/ionic-shopping-cart-2
Can you just check it again in the FoodKart V0.2
LikeLike
Thanks is ok but, and login undefined
LikeLike
I will be creating a video tutorial for configuring Foodkart V0.2. (Currently I am busy. Will create it by 2 to 3 weeks. Sorry for the delay.)
LikeLike
I will create a video tutorial on configuring Foodkart v0.2 as many are finding it confusing. (Currently I am busy. Will do it after 2-3 weeks.Sorry for the delay.)
If you want, you can check out this : http://www.arjunsk.com/html5/ionic-loginsignup-using-firebase/
LikeLike
I learned a lot thanks to you
LikeLike
Do check out the updated ionic cart !
LikeLike
Mantap Kang Arjun S K. Tutorialnya sangat Bermanfaat
LikeLike
Hii , when I clicked on signup button in console gives me this error: ionic.bundle.js : 21162 TypeError : Can not read property ‘created ‘ of undefined
at controllers.js : 188. please help me out this problem
LikeLike
did you fix it?
LikeLike
I, want to use only mysql database and i have no other choice.
LikeLike
Please find the updated Ionic Cart (FoodKart V0.2) here :
https://github.com/arjunsk/ionic-shopping-cart-2
Note:
*MySQL connection* :
Replace the MySQL connections variable in the server files.
https://github.com/arjunsk/ionic-shopping-cart-2/tree/master/%23SERVER_SIDE
*UPLOAD the server files in your server directory*
*Replace the API URL to your server directory url in Controller & Services*
https://github.com/arjunsk/ionic-shopping-cart-2/tree/master/www/js
Also find the latest Ionic Shopping Cart based on Firebase.
https://github.com/arjunsk/ionic-firebase-shopping-cart
LikeLike
Please find the latest Ionic Cart (FoodKart V0.2) here :
https://github.com/arjunsk/ionic-shopping-cart-2
Note:
*MySQL connection* :
Replace the MySQL connections variable in the server files.
https://github.com/arjunsk/ionic-shopping-cart-2/tree/master/%23SERVER_SIDE
*UPLOAD the server files in your server directory*
*Replace the API URL to your server directory url in Controller & Services*
https://github.com/arjunsk/ionic-shopping-cart-2/tree/master/www/js
LikeLike
I, want to use login and register with localhost database .
LikeLike
I bileave changing
var link = 'http://www.website.com/foodcart/server_side/signup.php';
to
var link = 'http://localhost/foodcart/server_side/signup.php';
would be enough if you are running WAMP(Server hosting software) on your PC.
LikeLike
not working. help me please.
I need a code login.. please..
LikeLike
Thanks bro, the code is working well. U just have to change settings for the code to work. Am using mysql database and it worked well. I just wanted the login part. Keep up the good work, much appreciation
LikeLike
Login function not completely work,When i give my real credentials it always says check your credentials ether details correct or wrong ….whats that error.i can’t find it.please help asap.
LikeLike
Why i cant run the app? Im using ionic serve
LikeLike
Can you show how to edit and update the registered user?
LikeLike
hi dont you have ionic v2 app with mysql
LikeLike
hi, how do i fix this error?
TypeError: Cannot read property ‘created’ of undefined
at controllers.js:51
at processQueue (ionic.bundle.js:29132)
at ionic.bundle.js:29148
at Scope.$eval (ionic.bundle.js:30400)
at Scope.$digest (ionic.bundle.js:30216)
at Scope.$apply (ionic.bundle.js:30508)
at done (ionic.bundle.js:24829)
at completeRequest (ionic.bundle.js:25027)
at XMLHttpRequest.requestLoaded (ionic.bundle.js:24968)
(anonymous) @ ionic.bundle.js:26799
(anonymous) @ ionic.bundle.js:23512
processQueue @ ionic.bundle.js:29140
(anonymous) @ ionic.bundle.js:29148
$eval @ ionic.bundle.js:30400
$digest @ ionic.bundle.js:30216
$apply @ ionic.bundle.js:30508
done @ ionic.bundle.js:24829
completeRequest @ ionic.bundle.js:25027
requestLoaded @ ionic.bundle.js:24968
XMLHttpRequest.send (async)
(anonymous) @ ionic.bundle.js:25005
sendReq @ ionic.bundle.js:24798
serverRequest @ ionic.bundle.js:24508
processQueue @ ionic.bundle.js:29132
(anonymous) @ ionic.bundle.js:29148
$eval @ ionic.bundle.js:30400
$digest @ ionic.bundle.js:30216
$apply @ ionic.bundle.js:30508
(anonymous) @ ionic.bundle.js:65428
defaultHandlerWrapper @ ionic.bundle.js:16792
eventHandler @ ionic.bundle.js:16780
triggerMouseEvent @ ionic.bundle.js:2953
tapClick @ ionic.bundle.js:2942
tapMouseUp @ ionic.bundle.js:3018
LikeLike
please how can i add information view on my markers
LikeLike