IONIC APP- get device id for post service($http.post) - angularjs

I'm trying to get the device id getUUID at the time of app login along with username and password. Is the right way to get device id and post it to the server for login.
controller.js
.controller('LoginCtrl', function($scope, $http,$rootScope,$window,$location,$cordovaDevice) {
$scope.login = function () {
var data ={
username : $scope.username,
password : $scope.password
};
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$http.post('login', data, config)
.success(function (data, status, headers, config) {
// $scope.DataResponse = data;
$location.path('#/tab/new-order');
})
.error(function (data, status, header, config) {
$window.alert("username or password incorrect");
});
console.log(device.cordova);
}
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
};
})
html code
<form action="" class="ki-login-form" method="post" accept-charset="utf-8">
<div class="form-group username">
<input type="text" class="form-control" name="username" value="" id="identity" placeholder="Your Name">
</div>
<div class="form-group pin">
<input type="text" class="form-control" name="password" value="" id="identity" placeholder="Your Pin">
</div>
<a type="submit" class="btns" ng-click='login()' >Login</a>
</form>
After login it has to be directed to a page href="#/tab/new-order" in the ionic tab

Add dependency injection $location in controller function like following -
.controller('LoginCtrl', function($scope, $http, $rootScope,$window,$location) {
// Your code
});
Solution for your added comment -
Use following -
Add device plugin : cordova plugin add org.apache.cordova.device
In your controller :
module.controller('MyCtrl', function($scope, $cordovaDevice) {
var uuid = $cordovaDevice.getUUID();
});

Change this
var data = $.param({
username : $scope.username,
password : $scope.password,
});
to
var data = {
username : $scope.username,
password : $scope.password,
};
UPDATE -
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}

Related

Not getting JSON object. AngularJS

I am new in Angular and trying to POST data , but I am getting undefined status. My JSON raw body is like this :
{
"Name": "Something",
"Description": "Something",
"Data": []
}
Name and description is from user input field and Data will be used later to push another JSON object in the array.
I tried but not getting exact output.
Controller:-
app.controller('postController', ['$scope', '$http', 'appService', function ($scope, $http, AppService) {
$scope.addInfos = [{
Name: $scope.name,
Description: $scope.description,
Data: []
}];
$scope.Create = function () {
$scope.addInfos.push({
'Name': $scope.Name,
'description': $scope.Description,
'Data': []
});
$scope.dataObj = {
Name: $scope.name,
Description: $scope.description,
Data: []
};
$http({
method: 'POST',
url: 'http://192.120.27.8:2000/api/Add',
data: $scope.dataObj
}).then(function (data, status, headers, config) {
alert("success");
console.log(data + $scope.Name + $scope.Description);
}, function (data, status, headers, config) {
alert("error");
});
$scope.name = '';
$scope.Description = '';
};
HTML page :-
<div class="input-group col-md-10">
<span class="input-group-addon" id="reg_input" >Name</span>
<input type="text" class="form-control" placeholder="" ng-model="addInfos.name">
</div>
<div class="input-group sepH_b col-md-10">
<span class="input-group-addon" id="reg_input" >Description</span>
<textarea name="reg_textarea" id="reg_textarea" cols="10" rows="3" class="form-control" ng-model="addInfos.description"></textarea>
</div>
<div class="col-md-4">
<a style="" class="btn btn-md btn-primary" ng-click="Create(addInfos)">Create</a>
</div>
The output which I can see in my console is [object Object]. What mistake am I doing here ?
NOTE:- Here I didn't mentioned Data: field as it will be predefined array as of now like this {data:[]} need to inject and pass Name and Description in JSON as I mentioned above.
SECOND also I need to push this over all output data to the Service to store for further use.
Thanks guys , now I can able push necessary datas inside the JSON I did second work around .
$scope.addInfos = {Data: []};
$scope.Create = function() {
$http({
method : 'POST',
url : 'http://192.120.27.8:2000/api/Add',
data : $scope.addInfos
}).success(function(data, status, headers, config) {
growl.success("Created a new File");
console.log(data);
},function (data, status, headers, config) {
growl.error("Something is wrong");
});
};
My second concern is still there , now how to push these data to a service. var something =[];?

symfony Post data through Angularjs

I'm trying to send ajax request with username and password through Angularjs to Symfony but the I can't access the post variables. Here is my code:
HTML:
<div>
<input type="text"
class="form-control defaultPassword"
ng-model="username"
placeholder="username">
</div>
<div class="form-group">
<input type="password"
ng-model="password"
class="form-control {% verbatim %}{{ passwordBox }}{% endverbatim %}"
placeholder="password">
</div>
<div>
<span>{% verbatim %}{{ message }}{% endverbatim %}</span>
<button id="submitBtn" class="btn" ng-click="login()">login</button>
</div>
AngularController
todoApp.controller("LoginController",
function LoginController($scope, $http){
$scope.username = "";
$scope.password = "";
$scope.login = Login;
function Login(){
$http({
method: 'POST',
url: '/api/login',
data: {
username: $scope.username,
password: $scope.password
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
alert("error");
});;
}
});
And here is the symfony controller:
/**
* #Route("/api/login")
* #Method("POST")
*/
public function apiLogin(Request $request){
$us = $request->request->get("username");
}
This method of retrieving the data doesnt work. I can see that the username and password are being sent but i have no access to them. Can you help me to find another way to get them in the symfony controller?
Angular
$http({
method : 'POST',
url : url,
headers : {'Content-Type': 'application/x-www-form-urlencoded'},
data : JSON.stringify(dataObj)
})
.success(function()
{
console.error("Done");
})
.error(function(dataObj)
{
console.error("Error");
});
Symfony
Include:
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Post;
Function:
/**
* POST Route annotation.
* #Post("/api/login")
*/
public function apiLoginAction(Request $request)
{
$parameters = $request->request->all();

Problems using $http POST

I am new in angular.js and I need to make form with 2 fields for numbers and when I click on submit i need to send to server with json for request result of suma. It will look like: 4 in first field , 4 in second field and on submit it will return result 8.
Thanks guys. Here is code:
<div ng-app="app" ng-controller="HttpGetController">
<p>Num1
<input type="number" name="num1" ng-model="num1" required />
</p>
<p>Num2:
<input type="number" name="num2" ng-model="num2" required />
</p>
<button ng-click="SendData()">Saberi</button> <hr />
{{ PostDataResponse }}
</div>
JS
var app = angular.module("app", []);
app.controller("HttpGetController", function ($scope, $http) {
$scope.SendData = function () {
var data = $.param({ num1: $scope.num1, num2: $scope.num2 });
var config = { headers : { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' } }
$http.post('localhost:3000', data, config)
.success(function (data, status, headers, config) {
$scope.PostDataResponse = data;
})
}
});
Get the input values and that will be automatically bind to scope. In your controller, just add those two operands.
$scope.sum = $scope.op1 + $scope.opt2;
then post the $scope.sum to server using $http.post() or thru $resource service.
$http POST with JSON Data Example
app.controller("HttpGetController", function ($scope, $http) {
$scope.SendData = function () {
var data = { num1: $scope.num1, num2: $scope.num2 };
$http.post('https://httpbin.org/post', data)
.then(function (response) {
$scope.PostDataResponse = response.data.data;
})
}
});
The DEMO on PLNKR

AngularJS HTML not updating after POST success

I'm trying to have an item in HTML update after a successful post query, but I can't seem to get it to work. Here's the HTML side:
<div class='container' ng-controller='MainController as inputControl' >
<div class='row well well-sm'>
<div class='col-md-6'>
<h2>Input Parameters</h2>
<form name='addform' ng-submit='inputControl.mainAddition()'>
<label>Number 1:</label>
<input ng-model='inputControl.inputData.num1' type="number" />
<br>
<label>Number 2:</label>
<input ng-model='inputControl.inputData.num2' type="number" />
<br>
<input type='submit' value='Add them!'/>
</form>
</div>
<div class='col-md-6'>
<h2>Result</h2>
<P>{{inputControl.resultData}}</P>
</div>
</div>
</div>
And here's the Angular side:
angular.module('pageLoader')
.controller('MainController',['$scope', '$http', function($scope, $http) {
var controller = this;
this.inputData = {};
$scope.resultData = 0;
this.mainAddition = (function() {
console.log(this.inputData);
$http({
method: 'POST',
url: '/functions',
data: this.inputData
})
.success( function(data, status, headers, config){
console.log(data);
$scope.resultData= (data);
});
this.inputData = {};
});
}]);
The console log shows the correct response from the server, but the resultData in HTML isn't populating.
Edit:
Yeah, sorry, I totally mixed up $scope and this. Find below working code
angular.module('pageLoader')
.controller('MainController',['$scope', '$http', function($scope, $http) {
this.inputData = {};
this.resultData = 0;
this.mainAddition = (function() {
var cntrlCache = this;
console.log(this.inputData);
$http({
method: 'POST',
url: '/functions',
data: this.inputData
})
.success( function(data, status, headers, config){
console.log(data);
cntrlCache.resultData= data;
});
this.inputData = {};
});
}]);
The easiest way to correct your snippet is to change $scope to controller in
$scope.resultData= (data);
since you've already declared var controller = this in the beginning.
Since the response is a html,you should use inject $sce service in the controller and do the following in the success method of the $http service
$scope.resultData = $sce.trustAsHtml(data)
Also its really a bad practice to have Async methods in the controller.Try to leverage angular services.
Please refer the SO Answer

Unable to call Angular Controller from Meteor template

I have updated my Meteor project from router to Iron-router;
I have created client / server side routing using Iron-router.
After updating to the iron router I am having a issue calling the LoginController when I hit the submit button it does not go to doLogin function. I am handing all the functionality in angular.doLogin function handles the login functionality.
client side route :
Router.route('/', 'login');
Router.route('/login', function () {
this.render('login');
});
login template:
<template name="login">
<div class="login-box" ng-controller="LoginController">
<h6>
<span>Welcome!</span>
Please log in using your username and password.
</h6>
<form ng-submit="doLogin();
isClick = false" name="myform" >
<fieldset>
<input type="text" id="login-username" placeholder="Username" name="username" ng-model="username" autocomplete="off" ng-click="msg = ''">
<input type="password" id="login-password" placeholder="Password" name="password" ng-model="password" autocomplete="off">
</fieldset>
<span>{{msg.message}}</span>
<button id="but" type="submit" ng-disabled="!username || !password">log in</button>
</form>
</div>
</template>
login controller:
angular.module('RSC').controller('LoginController', function ($scope, $route, $routeParams, $location, $http, $window, $sce) {
$scope.loggedIn = $window.sessionStorage['loggedIn'] ? angular.fromJson($window.sessionStorage['loggedIn']) : {status: false};
$scope.sessionid = Meteor.createSessionId();
// Add the login method
$scope.doLogin = function () {
var username = $scope.username;
var password = $scope.password;
// Adding the login to help generate the clientId
if (!$window.localStorage['clientid_' + username]) {
$window.localStorage['clientid_' + username] = Meteor.RSCRandomNumber();
}
// Get client id from local storage
var clientid = $window.localStorage['clientid_' + username];
// build the parameters
var dataSent = {"username": username, "password": password, "clientid": clientid};
return $http({
url: '/req/login',
method: 'POST',
data: jQuery.param(dataSent),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).error(function (err) {
$scope.msg = err;
}).success(function (result) {
//resolve the promise as the data
if (!result.hasOwnProperty('info')) {
$scope.username = "";
$scope.password = "";
$scope.msg = result.error;
$window.sessionStorage['userInfo'] = JSON.stringify({});
$window.sessionStorage['loggedIn'] = JSON.stringify({status: false});
} else {
$window.sessionStorage['userInfo'] = JSON.stringify(result.info);
$window.sessionStorage['loggedIn'] = JSON.stringify({status: true});
$scope.msg = "";
Session.set("vendorId", result.info.vendorId);
$location.path("/home");
}
});
};
});
I was able to fix the issue,Following solution helped me :https://github.com/Urigo/angular-meteor/issues/48
if (Meteor.isClient) {
Router.onAfterAction(function (req, res, next) {
Tracker.afterFlush(function () {
angular.element(document).injector().invoke(['$compile', '$document', '$rootScope',
function ($compile, $document, $rootScope) {
$compile($document)($rootScope);
if (!$rootScope.$$phase)
$rootScope.$apply();
}
]);
});
});
}

Resources