I trying to pass a form via $http.post from AngularJS to Sailsjs
My Sails Controller
create: function(req, res) {
console.log("req: "+req.param('user.firstName'));
res.send(req.param('user.firstName'));
},
My Angular Controller
function RegisterController($scope, $http) {
$scope.submit = function(){
console.log($scope.user.firstName); // works fine so far
$http.post('/user/create', $scope.user)
.success(function(data, status, headers, config) {
console.log("success");
})
.error(function(data, status, headers, config) {
console.log("error");
});
}
}
If I call my sails function like so /user/create?user.firstName=myFirstName its works fine. But if I try to read my passed data if I pass from angular. I don't know. I can't read the parm...
Someone any idea or a small example?
Cheers awesome community =)
You're posting the $scope.user object to your route, so it won't be namespaced under user. If the $scope.user contains, for example:
{firstName: "John", lastName: "Doe"}
then they would be available in your controller action as req.param('firstName') and req.param('lastName').
If you were to post the entire $scope object to /user/create (don't do this!), then you would be able to access req.param('user').firstName, req.param('user').lastName, etc. You still wouldn't be able to access things like req.param('user.firstName'), though; those are Angular expressions but they don't work server-side.
Related
I was updating my view by refreshing the page. I know that there is a better way. Can someone show me how to update the view data without refreshing the page:
myApp.service("deleteService", function ($http) {
this.removeRow = function (recId, compName, custName, docName) {
$http.post('DeleteRecord', { settingID: recId,companyName: compName,customerName: custName, documentName: docName } )
.success(function (data, status, headers, config) {
window.location.reload();
})
.error(function (data, status, header, config) {
});
}
});
Without seeing the rest of your code it is hard to be able to give you an exact answer, but I'm going to assume you have a service to get your data.
Approach 1) You can inject your "getService"? into this service and access the function you use to retrieve the data initially.
Approach 2) Instead of having a seperate service for each CRUD function, you can have a CRUD service that will manage the data manipulation, this way you can just call the "get" function without injecting a seperate service.
I have the following php:
public function getLoggedInUser()
{
if($this->isAjax())
{
exit (json_encode($_SESSION['User']));
}
}
And the following angular:
userModule.controller('UserController', [ '$http', function($http)
{
var userCtrl = this;
this.user = {};
$http.post('/User/getLoggedInUser', {request: 'ajax'}).success(function(data)
{
userCtrl.user = data;
});
}]);
i get code 302 but no result is found and the php script is not running.
What am i doing wrong?
Update
After debugging i the core of my PHP i can see that the variable request is not send to the server.
Why isnt it?
Note I’m no PHP expert, but I did some testing relating to one other AngularJS post request few days ago, which is quite similar to this one. So my solution here is based on my experience relating to that previous PHP post data experience. Also php manual for $_SESSION was used here.
First of all I’d put your php code in a getLoggedInUser.php file like below:
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
echo $_SESSION["User"];
}
?>
and then make some changes to the
UserController
//added $scope in the controller's function parameters, just in case
userModule.controller('UserController', [ '$http', function($scope, $http)
{
var userCtrl = this;
this.user = {};
//let’s pass empty data object
var dataObj = {};
$http.post('User/getLoggedInUser.php', dataObj).
success(function (data, status, headers, config)
{
console.log("success");
userCtrl.user = data;
//if the above doesn’t work, try something like below
// $scope.userCtrl.user = data;
})
.error(function (data, status, headers, config)
{
console.log("error");
});
}]);
I hope this helps with the issue.
Some notes: AngularJS is quite new to me, and if someone has different view how this post call should be made, then feel free to comment on this solution :-) Btw, I looked on some other php post issue solutions (without AngularJS) like this one, and I’m still uncertain what’s the best way of handling this post issue.
wher should i use the $http in angularjs?
in the controller or in the service?
i have already implement it in the service, but i want to execute not at the start of the app, i want to execute after some user actions, is this possible in the service?
'use strict';
/* Services */
// Demonstrate how to register services
// In this case it is a simple value service.
angular
.module('myApp.services')
.service(
'RestService',
function($http, $log) {
this.getERPProfile = function() {
var request = request;
request = JSON.stringify(request);
$http(
{
url : url,
method : "POST",
headers : {
'Accept' : 'text/xml',
'Content-Type' : '"text/xml; charset=\"utf-8\""'
},
dataType : 'xml',
data : request
}).success(
function(data, status, headers, config) {
var v1 = data;
return data;
$log.log(v1);
}).error(
function(data, status, headers, config) {
var v2 = status;
return data;
$log.log(v2);
});
};
and has someone a good documentation about the difference of factory and service? the angulajs site does not help me to understand.
thanks for your help!
Services are instantiated, only once, the first time they are called. They're used to share logic and expose data between controllers, for example. Controllers are the glue between the view and the model, like in any MVC framework.
Running it at the start of the app or not has nothing to do with doing the $http request from a controller or from a service. Mae the http request when you need it.
Notice that controllers are instantiated when angular finds <div ng-controller=whatever>... . If your http request is there, it'll be triggered. There was a similar question about services and factories a few weeks ago and another one about injecting a service in a controller.
This is the first time i am using Angular.js. So my workflow could be wrong.
How do i pass data from controller to the view
ng-view -> Displays html page using jade
When user clicks on submit button, i use $http on the controller and submit the request to the server.
The server returns me the necessary data back which i need to pass to another view.
My code snippet
function TrackController($scope,$http,$location,MessageFactory){
$scope.message = MessageFactory.contactMessage();
$scope.submit = function () {
var FormData = {
'track_applicationid': $scope.track_applicationid,
'track_email': $scope.track_email
}
$http({method: 'POST', url: '/track', data: FormData}).
success(function(data, status, headers, config) {
$scope.registeredDate = 'data.REGISTERED_DATE';
$scope.filedDate = data.FILED_DATE;
$location.path('trackMessage');
}).
error(function(data, status, headers, config) {
console.log('error');
});
}
}
In the above code, i want to pass registeredDate and filedDate to trackMessage view.
After going through the comments, i understood you are using one controller for two views.
If you want to set values to $scope.registeredDate and $scope.filedDate, You have to declare those objects globally using root-scope(Not recommended) or
use Angular values.
I recommended to use two different controllers.
I'm trying to connect to Untappd API trought angular.js; the API docs says
Whenever you are making a call to the API, you MUST pass both your Client ID and Client Secret as GET params like below
http://api.untappd.com/v4/method_name?client_id=CLIENTID&client_secret=CLIENTSECRET
with angular I have done this simply controller
function UntappdController($scope,$http) {
$http.get('http://api.untappd.com/v4/user/badges/jonnyjava?client_id=XXX&client_secret=XXX').success(function(data) {
alert('ok');
}).
error(function(data, status, headers, config) {
alert('ko');
});
}
UntappdController.$inject = ['$scope', '$http'];
but it doesn't work. (I get always KO)
So I'have tried tro a RESTful service. In this way
angular.module('BadgeServices', ['ngResource']).
factory('Badge', function($resource){
return $resource('http://api.untappd.com/v4/user/badges/jonnyjava/', {}, {
query: {method:'GET',params:{client_id: 'XXX', client_secret: 'XXX'}, isArray:true}
});
});
But this doesn't works too...
What I'm doing wrong? I'm new to angular. It looks simple but I'm missing something fundamental...
The error function is passed these variables: data, status, headers, config. Check their contents - I'm sure the server has some why of specifying what went wrong.
Sorry, I forgot it! Here is what I get with the error function..
data: status:0 headers:function (name) {
"use strict";
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
}config:[object Object]
Nothing helpful...
Solved! It was a CORS problem. If anyone is interest the solutions is here.
stackoverflow-Angularjs issue $http.get not working