SYmfony2 request can't get the post variable - angularjs

I'm trying to get the variable of a POST request in a symfony 2.4 controller. I usually have no issues on that but for this one...
this is how I call the controller:
var deferred = $q.defer();
$http({method:'POST',data:{dimensionpassed:dimension},url:Routing.generate('_API_getTree')}).success(function(result){
deferred.resolve(result);
});
return deferred.promise;
Now when I look in the console I can see the post request:
JSON
dimensionpassed
"ChartOfAccounts"
Source
{"dimensionpassed":"ChartOfAccounts"}
And here is the controller:
public function _API_getTreeAction(Request $request)
{
$test = $request->getContent();
var_dump($test);
$test = $request->request->get('dimensionpassed');
var_dump($test);
}
The first var dump gives me
"{"dimensionpassed":"ChartOfAccounts"}"
so there is something !
but the second is only "NULL"
what am I doing wrong ?

Apparently, Angularjs $http post variable don't go to the $_POST variable, hence it's impossible to have them in the $request->request->all().
However they appear "raw" as you can have them with this:$request->getContent();
Simply using $myvar = json_decode($request->getContent()) does the trick

I don't know angularjs at all, but that looks like JSON in the body, not request body parameters.
Try:
var_dump($request->request->all());
If you're sending post parameters you should see something like:
array 'dimensionpassed' => string 'ChartOfAccounts'
And the request body should look something like:
'dimensionpassed=ChartOfAccounts'
So you probably just need to get your POST from Javascript working properly (can't help there sorry).

Related

Mojolicious Angular POST JSON

i am new to Perl and Mojo and i've got one problem by receiving POST-Data from Angular:
My AngularCode is
var datainput = JSON.stringify({"test":"orcl"});
$http.post('http://localhost/perltest/perltest.pl/post', datainput)
.success(function(data, status, headers, config) {
console.log("post geschickt");
console.log(headers());
console.log(data);
console.log("data back: " + JSON.stringify(data));
alert(JSON.stringify(data));
})
My Mojo-Sub looks like:
post '/post' => sub {
my $self = shift;
my $json = $self->req->json;
print header(-type => "text/html");
print Dumper($json->{test});
};
app->start;
The Result i get is:
$VAR1 = undef; Content-Length: 0 Status: 404 Not Found Date: Fri, 20 Jan 2017 09:49:57 GMT
What is wrong?
It seems to me that $json = $self->req->json is not getting the JSON-String from POST ?
Angular passes posts in via the body of the request, so this is how I handle those.
post '/post' => sub {
my $self = shift;
my $json = $self->req->body;
#use Mojo::JSON qw(decode_json encode_json) at top of app
my $perl_hash = decode_json($json)
#Do something with the hash, like pass to a helper or model
$self->render(json => $return_from_model_or_helper);
};
Jquery posts will use the params and not the body.
The docs for the json method say that undef is returned if decoding didn't work or if the request was empty. You should first look at the request body.
warn Dumper $self->req->body;
This will output the raw request body to your application console or log. If you run morbo app.pl, that's your console window. Look at what you see. Is the content there? Is the content-type correct?
Then take it from there.
You can't just print in the middle of your route handler. You need to use the application object to render your content.
post '/post' => sub {
my $self = shift;
my $json = $self->req->json;
$self->render( text => $json->{test} );
};
This way, Mojolicious takes care of everything for you. There is also no need to set the content type explicitly. It's going to use something sensible automatically.
However, you're getting a 404 back. That might be because of the print, but I'm not sure.
The 404 Not Found indicates the resource is not found. Please double check if your application is available under http://localhost/perltest/perltest.pl/post.
You should not use print(), because it's not reliable (sometimes it works and sometimes not). If you want to log text into your console, please use $self->app->log->debug(). Mojolicious also has $self->dumper, you do not need to include the external module Data::Dumper.
Check the data which is actually send. You can use a service like http://requestb.in/. If you recieve correct JSON; I would strongly expect the URL is not correct (see point 1.)
I don't think you're supposed to JSON-stringify your object.
Try replacing your first angular line with this:
var datainput = {test: "orcl"};

Issues with single-requests in Restangular

I'm having a slight issue with my ability to consume REST data retrieved via Restangular in an angular controller. I have the following code which works fine for a list of accounts:
var baseAccounts = Restangular.all('accounts');
baseAccounts.getList().then(function(accounts) {
$scope.accounts = accounts;
});
This works perfectly for a list. I use similar syntax for a single account:
var baseAccount = Restangular.one('accounts');
baseAccount.getList(GUID).then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
I am using ng-repeat as the handling directive for my first request. I am attempting to bind with {{ account.name }} tags for the single request, but it does not seem to display any data despite the request being made properly. GUID is the parameter I must pass in to retrieve the relevant record.
I have combed through Restangular docs and it seems to me like I am composing my request properly. Any insight would be greatly appreciated.
EDIT: I've tried all of the solutions listed here to no avail. It would seem Restangular is submitting the correctly structured request, but when it returns it through my controller it shows up as just a request for a list of accounts. When the response is logged, it shows the same response as would be expected for a list of accounts. I do not believe this is a scoping issue as I have encapsulated my request in a way that should work to mitigate that. So, there seems to be a disconnect between Request -> Restangular object/promise that populates the request -> data-binding to the request. Restangular alternates between returning the array of accounts or undefined.
Have you looked at:
https://github.com/mgonto/restangular#using-values-directly-in-templates
Since Angular 1.2, Promise unwrapping in templates has been disabled by default and will be deprecated soon.
Try:
$scope.accounts = baseAccounts.getList().$object;
try:
var baseAccount = Restangular.one('accounts', GUID);
baseAccount.get().then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
The problem here is that it's expecting an array to be returned. I'm assuming that you are expecting an account object. Thus we need to use the get function, intead of getList()
The one() function has a second argument that accepts an id e.g. .one('users', 1). You can take a use of it.
CODE
var baseAccount = Restangular.one('accounts', 1); //1 would be account id
baseAccount.getList('account').then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
OR
var baseAccount = Restangular.one('accounts', 1); //1 would be account id
baseAccount.all('account').getList().then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
For more info take look at github issue
Hope this could help you, Thanks.

How can I build a get request with url that contains parameters

I am trying to do a get request to recover data from the server using the following url:
url = /api/projects/:projectId/scenarios
How can I do that using $http.get in AdngularJS?.
you might want to take a look at Restangular, I like its notation more than standard angularjs $http or $resource.
Restangular.setBaseURL('/api/');
Restangular.one('projects', projectId).all('scenarios').getList().then(function(data) {
myVariable = data;
});
Restangular

AngularJS Execute function after a Service request ends

I am using AngularJS Services in my application to retrieve data from the backend, and I would like to make a loading mask, so the loading mask will start just before sending the request. but how can I know when the request ends?
For example I defined my servive as:
angular.module('myServices', ['ngResource'])
.factory('Clients', function ($resource) {
return $resource('getclients');
})
.factory('ClientsDetails', function ($resource) {
return $resource('getclient/:cltId');
})
So I use them in my controller as:
$scope.list = Clients.query();
and
$scope.datails = ClientsDetails.get({
date:$scope.selectedId
});
So the question would be, how to know when the query and get requests ends?
Edit:
As a side note in this question I've been using using angularjs 1.0.7
In AngularJS 1.2 automatic unwrapping of promises is no longer supported unless you turn on a special feature for it (and no telling for how long that will be available).
So that means if you write a line like this:
$scope.someVariable = $http.get("some url");
When you try to use someVariable in your view code (for example, "{{ someVariable }}") it won't work anymore. Instead attach functions to the promise you get back from the get() function like dawuut showed and perform your scope assignment within the success function:
$http.get("some url").then(function successFunction(result) {
$scope.someVariable = result;
console.log(result);
});
I know you probably have your $http.get() wrapped inside of a service or factory of some sort, but you've probably been passing the promise you got from using $http out of the functions on that wrapper so this applies just the same there.
My old blog post on AngularJS promises is fairly popular, it's just not yet updated with the info that you can't do direct assignment of promises to $scope anymore and expect it to work well for you: http://johnmunsch.com/2013/07/17/angularjs-services-and-promises/
You can use promises to manage it, something like :
Clients.query().then(function (res) {
// Content loaded
console.log(res);
}, function (err) {
// Error
console.log(err);
});
Another way (much robust and 'best practice') is to make Angular intercepting your requests automatically by using interceptor (see doc here : http://docs.angularjs.org/api/ng.$http).
This can help too : Showing Spinner GIF during $http request in angular
As left in a comment by Pointy I solved my problem giving a second parameter to the get function as following:
$scope.datails = ClientsDetails.get({
date:$scope.selectedId
}, function(){
// do my stuff here
});

Angular $httpProvider transformResponse data contains local HTML DOM elements?

When I instantiate the following code in an AngularJS app, I get weird data in the transformResponse function (bottom of code). I'm not calling the $resource function from any controller, just loading the script in a browser. The data variable (see code) contains the HTML of the current partial, when loading the app.
This seems odd. Is this the way it's supposed to be?
var buddyServices = angular
.module('buddyServices', ['ng','ngResource'])
.factory('Buddy',
function ($resource) { console.log('resource');
return $resource('http://webservice.buddyplatform.com/v1/:service',
{service:'', BuddyApplicationName: 'xxx',
BuddyApplicationPassword: 'yyy'}
);
}
)
.config(function($httpProvider){
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.transformResponse = function(data) {
console.log(data);
return 'TEST: '+data;
};
});
=== EDIT ===
It just daunted on me: $httpProvider handles all http requests, so a page load is one of those. I'm guessing a bit now, but it seems probable. So, the question then becomes: Is there an "easy" way to constrain the data in the code above to only those requests performed by my service?
transformResponse takes another parameter headersGetter. You can use this to get the headers send with the response. Look for Content-Type header header. It should contain application/json

Resources