Angular scope variable storing different value compared to api response - angularjs

I am facing a very strange problem today with Angular, I have an api call whose response is giving (this is what i got from raw api call in new tab)
{ "startTime" : 1524021720000, "endTime" : 1524022800000 }
but after making an http call and storing response in $scope.dataSet variable this is what i am getting,
{ "startTime" : 1524001920000, "endTime" : 1524003000000 }
Below is the code snippet:
$http({url: testDetailsUrl, method: 'GET'})
.then(function(response) {
$scope.dataset = response.data;
console.log($scope.dataset.startTime, $scope.dataset.endTime);
}
I wanted to filter out value through angular pipe to show it as a time string, but i got strange results bucause of this change in variable values. Can anybody please explain me what happened here?
PS: I am using angular 1.4.9 and my browser's timezone is GMT+5:30..

According to me it is nothing to do with your browser's timezone GMT+5:30. I even faced similar issue, where WEB API is giving me new value(xyz) but in the $scope previous value(abc) used to display in the front end.
To fix this issue you can use below code,
$http({url: testDetailsUrl, method: 'GET', cache: false, headers: {
'Cache-Control' : 'no-cache'
}})

Related

angular: pass additional data with form submit

At the moment i am using below code and it is working fine.
$scope.processForm = function($scope.formData) {
$http({
method : 'POST',
url : 'process.php',
data : $.param($scope.formData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
Now i have one small requirement. I need to pass user id(uid) along with the form data.
In Jquery it is quite simple but I am new to angular and don't have much experience.
Any advise how i can pass the additional data in Angular.
Thanks
You can encapsulate your formData with your uid parameter togheter in an object expl :
var allData={'formData': $scope.formData, 'uid': $scope.uid}
And then pass in the allData Object to your post method data : allData.
If you encounter any problem getting data in you process.php (undefined data for example), you should let Angular pass data with content type application/json (default behavior of angularjs) and in your process.php you do like this :
$postContent= file_get_contents("php://input");
$req= json_decode($postContent);
$formData= $req->formData;
$uid= $req->uid;
Note that it will be great if you test with some static values first ( 'uid' : 2 ) to make sure that it works fine
you can send an object (associative array in php ) in $http data parameter:
$scope.processForm = function($scope.formData) {
console.log($scope.formData);
$http({
method : 'POST',
url : 'process.php',
data : {'data': $scope.formData,'userid':userid}, // no need to use $.param, even never see it in angular
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
see https://scotch.io/tutorials/submitting-ajax-forms-the-angularjs-way for details on how to get data in php side

Issue sending JSON in POST request to Play App

i am working on a project using Play Framework 2.4 using a simple Java template, as in many documentation i have seen, i just wrote a simple controller with my business methods and put the necessary paths on my route's file.
Now i am writing a client in Angular.js to invoke the logic written in the play app. It had work perfectly with GET methods, but when i try to do a POST from angular using the next lines:
$http({
method: 'POST',
url : rootURL + '/user/company',
data : {id : '123456' , name: 'xxxxxx'}
});
I receive a 404 Error. After several hours of forums searching, i found that the Play App is expecting application/x-www-form-urlencoded in the request content-type header.
So i modify my Angular call to the following:
$http({
method: 'POST',
url : rootURL + '/user/company',
data : {id : '123456' , name: 'xxxxx'},
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("&");
}
})
};
And the POST works perfectly on this way, but i wonder, is there any way so i can make a POST request to my play app where the content-type is set to application/json? How can achieve this?
UPDATE
Here is my controller code:
public class MyController extends Controller {
public Result myAction(){
//do funny stuffs
}
}
And my route file has the following
POST /path/action controllers.MyController.myAction()
Have you added #BodyParser.Of(BodyParser.Json.class) in your action method?
Also when you are doing POST to a different domain, first check you request to see if it's a POST, I don't know about AngularJS, but with Polymer, it sent a OPTION first during ajax POST to different domain, and I met very similar issue (wrong content type and 404) which is resolved by implementing an OPTION on server which accept POST.
To Fix that, you need to manually implement an OPTION, here's what to do:
First, In your routes file, add an entry to accept OPTION
OPTIONS /*url controllers.Application.optionCheck(url)
Then implement the optionCheck method which accept everything
public Result optionCheck(String url){
response().setHeader("Access-Control-Allow-Origin", "*");
response().setHeader("Access-Control-Allow-Methods", "POST");
response().setHeader("Access-Control-Allow-Headers", "accept, origin, Content-type, x-json, x-prototype-version, x-requested-with");
return ok();
}
And that's it

angular post method variables

I've gone several answers on this forum as well as checking angular's documentation but for some reason I'm stuck. I'm using angular and nodejs on the backend.
Attempt 1
var config = {
//data: $.param(token.body),
data: {'message': 'Hello world'},
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
$http.post("/admin/SignInWithCredentials", config)
Attempt 2
$http.post("/admin/SignInWithCredentials", {message: "Hello World"})
Nodejs end I see
console.log(request.query, request.params, request.method);
{} {} 'POST'
Assuming you're using body-parser you should be expecting the POST to contain a body. Try printing out request.body.
For reference, here is what is in request.query, and here is what's in request.params. It would make sense that both of these are empty objects from the examples you've given.
You are setting arguments incorrectly... data is not part of config object
$http.post(url, data, [config]);
Reference : $http.post() docs

Slim, Postman and AngularJs : $app->request->getBody() vs $app->request->post()

I'm a beginner. I've written a test application made of an AngularJs GUI on the client side and a PHP API on the server side.
This is the angular service handling the requests
myApp.factory('Book', ['$resource', 'API_URL', function($resource, API_URL){
return $resource(API_URL + '/books/:bookId', {bookId: '#bookId'}, {
get: { method: 'GET', isArray:true },
update: { method: 'PUT'},
save: { method: 'POST'},
delete: {method:'DELETE'},
});
}]);
When I submit a book from the Angular app I can catch the POST in Slim by using
$post_a = json_decode($app->request->getBody());
//$post_b = $app->request->post(); //this would be empty
When I use Postman and I perform a POST I can catch the POST in Slim by using
//$post_a = json_decode($app->request->getBody()); // this would be empty
$post_b = $app->request->post();
I don't get why there is this difference. Could you please explain?
Am I not meant to catch the post just with $app->request->post(); in both the cases? Why the post coming from Angular can be caught only with $app->request->getBody()?
The $app->request->post() method retrieves key/value data submitted in a application/x-www-form-urlencoded request. If the request uses a different content-type (e.g. application/json), you can retrieve the raw request body with the $app->request->getBody() method and decode it as necessary. Let me know if you have further questions.
You could still use
$post_b = $app->request->post()
in Slim.
As long as you call this REST service from html form (AngularJS) by passing the data as form value formatted instead of as JSON.
If in AngularJS you have the data in JSON format, you have to translate it first into form. Below is the example how to invoke this REST service:
Object.toparams = function ObjecttoParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
method: 'POST',
url: url,
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
myobject is the data in JSON format that is going to be created
Thanks Josh..Your answers works for me.
Steps to follow:
1.You need to send request in json format under raw tab like this:
{"username":"admin","password":"admin"}
2.You need to set Content-Type to application/json in the headers.
That's it and it will work.

Retrieve data from a JsonP proxy in sencha touch

I am trying to get the data from a JSONP proxy in sencha touch 2.3(I am using sencha architect 3 to develop). I was successfully able to place jsonp call and get the data back. But I am not getting how to separate every single element of json response. Here is my json Response:-
{"data":[{ "PLANTNUM": "1557", "ROUTEID": "90625", "DELIVERYDATE": "2014-02-12T00:00:00-06:00", "MESCOD": "15", "MESFCT": "DLV", "ORIGID": "HH", "JMSTIME": "02/11/2014 00:11:21", }],"success" : true}
Here is my function
success: function(response){
console.log(response);
var temp=response.data.PLANTNUM;
console.log(temp);
}
I can see below in my console:-
Here is my jsonP request
Ext.data.JsonP.request({
url: 'http://localhost:12608',
callbackKey: 'cbfn',
params: {
method: 'sapout',
type: 'sap',
ordnum: '1034986850'
}
I tried using response.PLANTNUM but that is also not working. It always shows undefined
Can anyone help me out here.
Thanks
data is an array, so you want response.data[0].PLATINUM.

Resources