Post method angular JS - angularjs

.controller('LoginConnect', ['$scope', 'connecting',
function(connecting, $scope){
$scope.user = {};
var inputLogin = $scope.user.login;
var inputPassword = $scope.user.password;
$scope.connect = function (){
connecting(ConnectingFactory);
};
}
])
.factory('connecting', ['$http','$q', function ($http,$q,inputLogin, inputPassword, ConnectingFactory){
var ConnectingFactory = {};
console.log(ConnectingFactory);
ConnectingFactory.login = function(){
var deferred = $q.defer();
$http({
method: 'POST',
url: "http://api.tiime-ae.fr/0.1/request/login.php",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {login: inputLogin, password: inputPassword}
})
.success(function(result){
deferred.resolve(result);
var promise = deferred.promise;
promise.then(function(result){
console.log(result);
// jsonTab = angular.fromJson(result);
// $scope.result = result["data"];
// $scope.user.token = result["data"];
});
})
};
return ConnectingFactory;
}]);
;
And here the HTML :
<!-- User Connection -->
<form name="userConnect" ng-submit="connect()" novalidate ng-controller="LoginConnect">
<label>
Enter your name:
<input type="text"
name="myEmail"
ng-model="user.login"
/>
</label>
<label>
Enter your Password:
<input type="password"
name="password"
ng-model="user.password"
/>
</label>
<input type="submit" value="Connection">
<p>resultat : {{result}}</p>
<p ng-model="user.token">
token : {{mytoken}}
</p>
<p ng-model="user.datab">
datas : {{datab}}
</p>
<br><br><br>
</form>
Hi, I m new in Angular Js developpement, i have no error but not any data in sent to the API. I think their is no link between my function "connect()" and the factory. Could you help me pls ?

Don't use the success method either way.Both methods have been deprecated.
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
Here is the shortcut method
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
Here is a longer GET method sample
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Official Documentation
Regarding the factory , call it correctly as ConnectingFactory.login().
Also, the order here is incorrect, as pointed out by Harry.
['$scope', 'connecting',
function(connecting, $scope){

Related

The data alone is missing when I try to send from Angular.js to Node.js

I am trying to send data from my Angular.js controller to Node.js backend. I succeeded in making a MongoDB entry when the request is raised.But the data is missing in the MongoDB entry. I am stuck and can't proceed with my app anymore. Can anyone give me a clear explanation why I am not able to send the form data to the Node.js.
I had put my schema of the data here:
var common = require('../common');
var inviteeSchema = common.Schema({
email: String
});
var Invite = common.conn.model('Invite', inviteeSchema);
module.exports = Invite;
I have enclosed the routing code here.
router.route('/addtoinvitelist').post(function (req, res, next) {
var invite =new Invite(req.body);
invite.save(function(err,email){
if(err) throw err;
res.json({message:"your mail id is stored in our database we will soon send you an invite"})
});
});
My HTML form goes here
<form action="#">
<div class="form-group">
<label for="subcribeNewsletter" class="control-label">INVITE FORM<br> <small>We are happy to invite you to medicoshere, So please enter your email ID in the below form.</small></label>
<div class="input-group input-group-in input-group-sm">
<div class="input-group-addon"><i class="fa fa-envelope text-belpet"></i></div>
<input class="form-control" id="subcribeNewsletter" placeholder="name#mail.com" ng-model="useremail" required>
<div class="input-group-btn">
<button type="submit" class="btn btn-default text-belpet" ng-click="AddToInviteList(useremail)"><strong>OK</strong></button>
</div>
</div>
</div><!-- /.form-group -->
</form><!-- /form -->
my angular service functions goes here
`this.AddToInviteList = function (email, cb) {
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}, // set the headers so angular passing info as form data (not request payload)
data:"email"
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}`
Controller function is here
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.email = {};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}
});
Pass email as json object { 'email' : email }.
Just try this code:
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
Controller :
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
$scope.user = {
email : $scope.useremail
};
UserServices.AddToInviteList($scope.user, function (dataresponse) {
console.log(dataresponse);
})
}
});
In server side you can access the email by calling 'req.body.email'
Change your model name in HTML input element with email and send request as
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/json'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
and get it at backend side as
req.body.email
I think that should work!
Update
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}

File upload with other data in angularjs with laravel

I want to upload file and other data with angularjs. I am usign FormData but I receive blank array from server side.
This is my form
<form ng-submit="beatSubmit()" name="beatform" enctype="multipart/form-data">
<input type="text" id="beat-name" ng-model="beatData.title" required="required" />
<input type="file" id="image" file-model="image" />
<input type="file" id="tagged_file" file-model="tagged_file" accept="audio/mp3" />
<input type="file" id="untagged-beat" file-model="untagged_file" accept="audio/mp3" />
<input type="text" class="form-control" id="price1" ng-model="beatData.price1">
</form>
Here is my Controller and FileModel directive
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
// This is controller part in another file
$scope.beatSubmit = function(){
var image = $scope.image;
var tagged_file = $scope.tagged_file;
var untagged_file = $scope.untagged_file;
var response = BEAT.uploadBeat($scope.beatData,image,tagged_file,untagged_file);
response.success(function(response){
console.log(response);
});
}
And this is my service
uploadBeat:function(data,image,tagged_file,untagged_file){
var fd = new FormData();
fd.append('image', image);
fd.append('tagged_file', tagged_file);
fd.append('untagged_file', untagged_file);
angular.forEach(data, function(value, key) {
fd.append(key,value);
});
console.log(fd); // fd is null , I don't know why?
var req = {
method: 'POST',
transformRequest: angular.identity,
url: 'api/upload_music',
data: fd,
headers:{
'Content-Type': undefined,
}
}
return $http(req);
}
When I tring to get these data from server side It will return null. I spent more time to resolve this But I didn't got any solution. If anyone know Please help me out. Thanks in advance.
Add this header details to the $http
$http({
method: 'POST',
url: '',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept':'*/*',
'Content-type':'application/x-www-form-urlencoded;charset=utf-8'
},
params:data,
timeout:4000
});
Laravel not allowed to submit ajax request without same domain policy
I found an error, I have to remove enctype="multipart/form-data" from form.

Link between controller and factory

.controller('LoginConnect', ['$scope', 'connecting',
function($scope, connecting){
$scope.user = {};
$scope.connect = function(){
connecting();
};
}
])
.factory("connecting", ["$scope", "$q", "$http", function ($scope,$q, $http){ var deferred = $q.defer();
$http({
method: 'POST',
url: "http://api.tiime-ae.fr/0.1/request/login.php",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {login: $scope.user.login, password: $scope.user.password}
})
.success(function(result){
deferred.resolve(result);
var promise = deferred.promise;
promise.then(function(result){
jsonTab = angular.fromJson(result);
$scope.result = result["data"];
$scope.user.token = result["data"];
});
})
}])
;
and here the HTML:
<!-- User Connection -->
<form name="userConnect" ng-submit="connect()" novalidate ng-controller="LoginConnect">
<label>
Enter your name:
<input type="text"
name="myEmail"
ng-model="user.login"
/>
</label>
<label>
Enter your Password:
<input type="password"
name="password"
ng-model="user.password"
/>
</label>
<input type="submit" value="Connection">
<p>resultat : {{result}}</p>
<p ng-model="user.token">
token : {{mytoken}}
</p>
<p ng-model="user.datab">
datas : {{datab}}
</p>
<br><br><br>
</form>
Hi, I am new in Angular JS, could you help me pls to fixe this. I have the following error :$scopeProvider <- $scope <- connecting
I think this error is due to the link betwwen controller and factory
Your service needs to return something.
instead try:
.factory("connecting", ["$scope", "$q", "$http", function connect($scope,$q, $http){
return function() {
//your method
};
}])
Here is the code Example of linking controller and factory similar to yours. You simply return the something from the factory.
.controller('LoginConnect', ['$scope', 'connecting',
function($scope, connecting) {
$scope.user = {};
$scope.connect = function() {
connecting.login($scope.signupData.username, $scope.signupData.password).success(function(data) {
//
$sessionStorage.userid = data.UserId;
$sessionStorage.token = data.access_token;
if (data.UserId != "") {
$state.go('app.editProfile');
}
})
.error(function(data, status, headers, config) {
console.log("http error", data);
});
};
}
])
.factory('connecting', ["$scope", "$q", "$http", function ($scope,$q, $http){
var urlBase = 'http://apple.com:7071';
//Login
return {
login: function(loginusername, loginpassword) {
return $http({
method: 'POST',
url: urlBase + '/Login',
data: {
username: loginusername,
password: loginpassword,
grant_type: 'password'
},
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
})
}
}
}])
Fatcory needs to return an Object.
.factory("connecting", ["$scope", "$q", "$http", function ($scope,$q, $http){
var ConnectingFactory = {};
ConnectingFactory.login = function(){
var deferred = $q.defer();
$http({
method: 'POST',
url: "http://api.tiime-ae.fr/0.1/request/login.php",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {login: $scope.user.login, password: $scope.user.password}
})
.success(function(result){
deferred.resolve(result);
var promise = deferred.promise;
promise.then(function(result){
jsonTab = angular.fromJson(result);
$scope.result = result["data"];
$scope.user.token = result["data"];
});
})
};
return ConnectingFactory;
}]);

Function in angular keeps getting executed

I have this template in my project:
<script type="text/ng-template" id="/challenges.html" ng-controller="ChallengeCtrl">
<main>
<h3 class="headingregister">Start challenge reeks</h3>
{{getUser()}}
<form name="startChallengesForm" ng-submit="getChallenges()">
<button type="submit" class="btn btn-primary">Doe de challenges!</button>
</form>
</main>
</script>
The getUser() function should display the current logged in users info.
This is the ChallengeCtrl:
app.controller('ChallengeCtrl', ['$scope', 'auth',
function($scope, auth) {
$scope.isLoggedIn = auth.isLoggedIn;
$scope.currentUser = auth.currentUser;
$scope.logOut = auth.logOut;
$scope.getUser = function(){
auth.getUser(auth.currentUser()).getValue(function(value){
return value;
});
};
}]);
this is auth.getUser:
auth.getUser = function(usr){
return{
getValue: function(callback){
$http({
method: 'POST',
url:'http://groep6api.herokuapp.com/user',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data : {username: usr}
}).then(function (result) {
//return result.data;
callback(result.data);
});
}
}
}
the problem is when I run the page, I see in developer tools that the function is being called over and over again, it should only display the users info.
How can I accomplish this?
Function calls in templates get executed each digest cycle. Simply fetch the user once in your controller and assign the value to the scope
auth.getUser(auth.currentUser()).getValue(function(value){
$scope.user = value;
});
and in your template, instead of {{getUser()}}
{{user}}

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

Resources