$http.post from angular form not sending any data - javascript

I have a form that is posting /api/tradelink but it doesn't send any body or data with it.
HTML :
<form ng-submit="sendTradelink()">
<md-input-container class="md-accent">
<label>Enter your tradelink</label>
<input ng-model="tradelink">
</md-input-container>
<md-button type="submit" class="md-raised md-accent">Send</md-button>
</form>
Services :
.factory('Auth', ['$http', '$api', '$window', function ($http, $api, $window) {
var authFactory = {};
authFactory.authenticate = function(){
$http.post($api.url + 'auth')
.successs(function(url){
$window.location.href = url;
});
};
authFactory.send = function () {
return $http.post($api.url + 'tradelink');
};
return authFactory;
}]);
Controller ;
.controller('AppCtrl', ['$scope', 'Auth', '$location', '$cookies', function ($scope, Auth, $location, $cookies) {
var sidTemp = 'needtomakeitanewvalue';
$scope.checklogin = function () {
$scope.sid = $cookies.get('sid2');
console.log($scope.sid);
}
$scope.sendTradelink = function () {
Auth.send($scope.tradelink)
.success(function (res) {
$scope.sidTemp = 'needtomakeitanewvalue';
$cookies.put('sid2', sidTemp);
$location.path('/');
});
}
$scope.auth = function () {
Auth.authenticate();
}
}])
Server side holding api request, nothing inside req.body or req.params. Both show as empty objects.
api.post('/tradelink', function(req, res){
console.log(req.user.steamId);
console.log(req.params);
console.log(req.body);
res.json({
success: true,
message: 'tradelink received'
})
});

Check the Angular docs for $http.post
You are calling Auth.send($scope.tradelink), but your authFactory.send() function needs to accept this tradelink value and then be used as a data param to $http.post()
So:
authFactory.send = function (tradelink) {
return $http.post($api.url + 'tradelink', {tradelinkId: tradelink });
};

Related

Angular load data from server and display information on separate page

I have a page where I display all usernames. Now I want to click on one of these usernames make a call to server to retrieve more information and display it on separate User page. (First name, last name, etc)
My problem is that when I click on username page opens but fields are not populated. Could you please review my code and suggest what I am doing wrong there?
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "pages/login_page.html"
})
.when("/userpage", {
controller : 'UserController',
templateUrl : "pages/user_page.html"
})
.when("/allusers", {
controller : 'AllUserController',
templateUrl : "pages/all_users.html"
});
});
This is my login code. After user authenticated it can see all other users. So I am changing view to #allusers
app.directive("loginForm", function (AuthorizedHttp, ConfigurationRepository, UserObj) {
return {
restrict: 'E',
scope: {
},
templateUrl: 'templates/login-template.html',
replace: 'true',
controller: ['$scope', '$http', '$window',
function($scope, $location, $window) {
$scope.loginError = false;
$scope.login = function () {
$scope.loginError = false;
UserObj.setState(null, null, $scope.username, $scope.password, null);
AuthorizedHttp.get('http://{0}/account/user/login'.format(ConfigurationRepository.getBackendHostName()))
.success(function (response) {
UserObj.setState(response.first_name, response.last_name, response.email, $scope.password, response.role, response.timezones);
$window.location = "#allusers";
})
.error(function (err, status) {
$scope.username = '';
$scope.password = '';
$scope.loginError = true;
})
}
}
]
}
});
Code below responsible to make a call and retrieve all users. Works fine.
app.controller('AllUserController', function ($scope, AuthorizedHttp, ConfigurationRepository, UserObj, UserCurrent, TimezoneService) {
$scope.init = function () {
TimezoneService.getAllUsers()
.success(function (response) {
$scope.users_emails = response.map(function (item) {return item.email})
})
.error(function (err, status) {
alert('Error loading all users ')
});
};
});
HTML to display all usernames. Also set ng-click to pass a username as parameter to retrieve required user.
<div ng-controller="AllUserController" ng-init="init()">
<div ng-controller="UserController">
<div ng-repeat="email in users_emails" class="item-unchecked">
<a ng-click="getUser(email)">{{email}}</a>
</div>
</div>
</div>
User controller. Executed every time I click on username link.
app.controller('UserController', function ($scope, AuthorizedHttp, ConfigurationRepository, UserObj, UserCurrent, TimezoneService, $window) {
$scope.user_display_name = 'Now set yet';
$scope.getUser = function(username) {
TimezoneService.getUser(username)
.then(function (response) {
$scope.required_user = response.data;
$scope.user_display_name = '{0} ({1})'.format(response.data.first_name, response.data.email);
$scope.user_timezones = response.data.timezones.map(function (item) {
return item.timezone_name
});
$scope.user_role = response.data.role;
$window.location = '#userpage';
});
};
});
As a result user_page.html is loaded but all fields are not set. I don't understand why since I am setting a scope value before I change a $window.location.
Remove ng-controller="UserController" from your HTML
Create a function in your AllUserController like that
$scope.customNavigate = function(routeToNavigate, routeParameter){
$location.path("/" + routeToNavigate + "/" + routeParameter);
}
Change .when("/userpage", { to .when("/userpage/:email", {
Change ng-click="getUser(email)" to ng-click="customNavigate("userpage", email)"
Inject $routeParams to your UserController
Change $scope.getUser = function(username) { to function getUser (username) {
Call getUser($routeParams.email) in your UserController.

Increment the Mongoose query limit by button click/scroll in AngularJS

I want to increment the data via Button click or scroll.
I have a function which loads the data after button click loadDataQueryDB(param, param, param). With that, I am passing data to MongoDB query.
Well how can I increment my var limit = 50; + 5; after each button click?
Node.js
router.get('/load', function(req, res) {
var skip = 0;
var limit = 50;
var place_val = req.query.place;
var category_val = req.query.category;
var specCategory_val = req.query.specCategory;
if(category_val, specCategory_val, place_val){
Experiences
.find({category : category_val, city:place_val})
.lean()
.skip(skip)
.limit(limit)
.exec(function(err, docs_accommo) {
res.send(docs_accommo);
console.log("First");
});
}
});
Angular.js
app.controller('loadData', ['$scope', '$http', '$window', '$upload', '$rootScope',
function($scope, $http, $window, $upload, $rootScope) {
$scope.loadDataQueryDB = function(place_value, category_value, specCategory_value){
console.log(place_value);
console.log(category_value);
console.log(specCategory_value);
$scope.datafront = [];
var options = {
place : place_value,
category: category_value,
specCategory : specCategory_value
};
$http.get('/load',
{params: options})
.success(function(data) {
$scope.datafront = data;
});
};
});
HTML
<div ng-click="loadDataQueryDB(place, category, specCategory)">
<div ng-repeat="x in datafront | limitTo:? track by x._id" ng-cloak>
{{x}}
</div>
</div>
<button class="btn btn-default" style="float:right; margin-bottom:20px;"/>
Something like the code below, using services and http promises, the data returned form the server its on promise.data.
app.controller('loadData', ['$scope', '$http', '$window', '$upload', '$rootScope','dataService',
function($scope, $http, $window, $upload, $rootScope, dataService) {
$scope.loadDataQueryDB = function(place_value, category_value, specCategory_value){
console.log(place_value);
console.log(category_value);
console.log(specCategory_value);
$scope.datafront = [];
var params = {
place : place_value,
category: category_value,
specCategory : specCategory_value
skip : $scope.skip,
limit : $scope.limit
}
dataService.getData(params).then(function(promise){
$scope.dataFront = promise.data;
//Increment the limit by ten
$scope.limit =+ 10;
})
};
});
app.module('dataService').factory('dataService',['$http',function ($http) {
var service = {};
factory.getData= function (params) {
var promise = $http({
method: 'GET',
url: '/load',
params: params
});
return promise;
}
return service;
}]);
You should have only the gets that return views on the router and the rest of the get and post calls on a service, at least I develop like that and its more confortable.

Send data through a POST request from Angular factory

I have this in the controller
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
$scope.formTodoText = '';
};
});
and this in the factory
angular.module('myApp')
.factory('TaskFactory', function ($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
console.log(1, params);
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log(2);
console.log('data', data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTask: function(taskData) {
console.log('taskData', taskData);
return sendTasks('/task/save', {
taskData : taskData
})
}
}
});
all I need is to know, how to send the data from the controller to the factory in order to do the POST to the specified route ?
You just need to call the function/method inside factory with the required params.
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
TaskFactory.sendTask({data : $scope.formTodoText})
$scope.formTodoText = '';
};
});
You can follow Dan Wahlin blog post.
Controller:
angular.module('customersApp')
.controller('customersController', ['$scope', 'dataFactory', function ($scope, dataFactory) {
$scope.status;
dataFactory.updateCustomer(cust)
.success(function () {
$scope.status = 'Updated Customer! Refreshing customer list.';
})
.error(function (error) {
$scope.status = 'Unable to update customer: ' + error.message;
});
}
Factory:
angular.module('customersApp')
.factory('dataFactory', ['$http', function($http) {
var urlBase = '/api/customers';
dataFactory.updateCustomer = function (cust) {
return $http.put(urlBase + '/' + cust.ID, cust)
};
}
Hope that solve your problem.
You can call the function directly on the TaskFactory that you pass into the controller as a dependency.
I've cleaned up your code a bit and created a plunk for you here:
And here's the code:
Controller
(function(angular) {
// Initialise our app
angular.module('myApp', [])
.controller('TaskController', function($scope, TaskFactory) {
// Initialise our variables
$scope.todos = [];
$scope.formTodoText = '';
$scope.addTodo = function() {
// Add an object to our array with a 'text' property
$scope.todos.push({
text: $scope.formTodoText
});
// Clear the input
$scope.formTodoText = '';
// Call function to send all tasks to our endpoint
$scope.sendTodos = function(){
TaskFactory.sendTasks($scope.todos);
}
};
});
})(angular);
Factory
(function(angular) {
angular.module('myApp')
.factory('TaskFactory', function($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log('data: ' + data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTasks: sendTasks
}
});
})(angular);

Cannot POST / angular routing

I've searched and can't quite find someone with the same circumstances, I'm using angular routing to perform CRUD on a mock db.json server and when I execute the 'update' function, it changes the value in the database, but always redirects me to a blank page that just says 'Cannot POST /'. Even though the request actually went through. I'd just like it to return to the /clients page once the request is finished. I'm using browserify to include angular and angular-route. Thanks in advance :)
// Router
var UNRealtyApp = angular.module('UNRealtyApp', ['ngRoute'])
UNRealtyApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/clients', {templateUrl: 'app/views/clients.html', controller: 'clientListCtrl'})
.when('/add-client', {templateUrl: 'app/views/client-add.html', controller: 'clientAddCtrl'})
.when('/edit-client/:id', {templateUrl: 'app/views/client-edit.html', controller: 'clientEditCtrl'})
.otherwise({redirectTo: '/404'});
}]);
//Client CRUD
UNRealtyApp.controller('clientListCtrl', function ($scope, $http){
console.log('clientListCtrl activated')
$http.get('http://localhost:3000/clients/').success(function(data) {
$scope.clients = data;
})
})
UNRealtyApp.controller('clientAddCtrl', function ($scope, $http, $location){
console.log('clientAddCtrl activated')
$scope.master = {};
$scope.activePath = null;
$scope.add_new = function(client, AddNewForm) {
console.log('add_new activated')
$http.post('http://localhost:3000/clients/', client).success(function(){
$scope.reset();
$scope.activePath = $location.path('/clients');
});
$scope.reset = function() {
console.log('reset activated')
$scope.client = angular.copy($scope.master);
};
$scope.reset();
}
})
UNRealtyApp.controller('clientEditCtrl', function ($scope, $http, $location, $routeParams){
console.log('clientEditCtrl activated')
var id = $routeParams.id;
// $scope.activePath = null;
$http.get('http://localhost:3000/clients/' + id).success(function(data) {
$scope.clients = [data];
});
$scope.update = function(client){
console.log('update activated')
$http.put('http://localhost:3000/clients/' + id, client).success(function(data) {
$scope.clients = data;
$scope.activePath = $location.path('clients');
});
};
$scope.delete = function(client) {
console.log('delete activated')
var deleteClient = confirm('Are you sure you want to delete?');
if (deleteClient) {
$http.delete('http://localhost:3000/clients/' + client.id);
$scope.activePath = $location.path('clients');
}
}
})

Angular RouteParams send ID

I am trying to send an ID through to a controller using $routeParams via a factory but it is not working.
My $routeProvider:
.when('/event/:eventId', {
templateUrl : 'pages/event_detail.html',
controller : 'eventPageCtrl'
});
My factory:
myApp.factory('eventRepo', ['$http', function($http) {
var urlBase = 'php/api.php';
var eventRepo = {};
eventRepo.getEvent = function (id) {
return $http.get(urlBase + '?eventID=' + id);
};
return eventRepo;
}]);
My Controller:
myApp.controller('eventPageCtrl', ['$scope', '$routeParams', 'eventRepo',
function ($scope, $routeParams, eventRepo) {
$scope.getEvent = function (id) {
eventRepo.getEvent($routeParams.eventId)
.success(function (data) {
$scope.eventsDetail = data;
})
.error(function (error) {
$scope.status = 'Error retrieving event! ' + error.message;
});
};
}]);
When handling $http.get() inside the controller and not with the factory it works fine so I think I am not passing my $routeParams correctly? Perhaps this line is causing the issue eventRepo.getEvent($routeParams.eventId)?
This works currently, but trying to use $http.get() outside the controller:
myApp.controller('eventPageCtrl', function($scope, $http, $routeParams) {
$http.get("php/api.php?eventID="+$routeParams.eventId).success(function(data){
$scope.eventsDetail = data;
});
});
how about using resolve in your routeProver and returning the eventId and then injecting it in the controller .. example :
$routeProvider:
.when('/event/:eventId', {
templateUrl : 'pages/event_detail.html',
controller : 'eventPageCtrl',
resolve : {
eventId: function($route, $location) {
var eventId = $route.current.params.eventId;
return eventId;
});
Controller:
myApp.controller('eventPageCtrl', ['$scope', 'eventId', 'eventRepo',
function ($scope, eventId, eventRepo) { //add it as a dependency
$scope.eventId = eventId; //you can check this to see if its being assigned
$scope.getEvent = function (eventId) { //Edit: eventId added here
eventRepo.getEvent(eventId) //Edit: eventId passed
.success(function (data) {
$scope.eventsDetail = data;
})
.error(function (error) {
$scope.status = 'Error retrieving event! ' + error.message;
});
};
}]);

Categories

Resources