Pass Data List from angularjs to webservice? - angularjs

I'm working on app in ionic 1 platform using angularjs, in which I want to Pass List of object to Web-service, How can I do it?
I have tried doing this but was not able to send any Data..
Here is my code and how to pass list of object in data: $scope.AddNew
$http({ url: $rootScope.HostName + '/bulk', dataType: 'json', method: 'POST', contentType: "application/json; charset=utf-8", data: $scope.AddNew, headers: { 'content-type': 'application/json' } }).success(function (response) { alert("Success"); }).error(function (error) { });
If there is another approach or way to do it then please do help
Thanks in advance.

Assuming your $http call is in the controller where you can access $scope.
The way you had passed is correct, but at the server side you should accept your request body as an Array of objects.
If your server side is java spring app,
You would design your method with #RequestBody YourClass[] objs

I think your code is correct, just so it is simple and readable I would suggest this format:
$http.post($rootScope + '/bulk', $scope.AddNew).then(function(response) {
alert("Success");
}, function(error) {
})
The promise structure in AngularJS has since been updated. In regard to your question, the code should work fine if you can access AddNew through your $scope. Make sure you are handling your requests properly in the backend. Try logging for checking if data is sent and received.

Related

Angular $http post call passing data issue to GO backend

I am trying to get access to backend written in GO which in 99% is good (problem does not lay there).
For now I just created simplest call which stay in controller (it will be in service in future) to register new user. Although I hardcoded data which I am passing the response says 403 forbidden. In powerShell shows reason of 403:
RegistrationForm parse - email: , nick:
Validation failed for email - blank
It looks like I am not passing my data correctly because email is blank. Please take a look at my code:
$ctrl.fake_registerSubmit = function() {
$http({
url: 'http://localhost:3000/v1/sign_up',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
data: {
email: 'check#onet.pl',
nick: 'borysxoxo',
password: 'admin12312',
password_confirmation: 'admin12312'
}
})
.then(function successCall(response, post) {
console.log('user added');
}, function errorCall(respone) {
console.log('error callback');
console.log(respone);
})
};
This screenshot presents API documentation which I am trying to access:
link
What am I doing wrong? Is there other way to pass data?
You are sending some json data with the wrong Content-Type.
I see 2 options, either change Content-Type in your header to:
'Content-type' : 'application/json'
or transform your payload to:
data: "email=check#onet.pl&nick=borysxoxo&password=admin12312&password_confirmation=admin12312"

Angular: $http change method on adding data with post

I am using fuse template and accessing my web service by using $http, its working fine if i am using method: 'POST' without send any data but whenever i am adding some data with post like: data: {text:'test'} and send request to my web service its change the method type POST to OPTIONS.
My Code:
$scope.submit = function(){
$http({
method: 'POST',
url: 'http://www.example.com/api-link',
data: {test: 'hello'},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(result){
console.log(result);
});
}
When i am checking in browser network its showing method type OPTIONS. Can anyone please tell what is wrong in my code?
Thanks

ionic $http post not sending data

I am trying to post data to a web service but the data is missing.
Here is the code
var product = {
CategoryID: 'test'
};
$http({
url: URL,
method: "POST",
data: product,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data,status,headers,config) {
console.log(data);
})
.error(function(data,status,headers,config) {
console.log(data);
});
The POST data on the server is empty.
I have set up Access-Control-Allow-Origin,Access-Control-Allow-MethodAccess-Control-Allow-Headerss and Access-Control-Allow-Headers on the server.
This API works fine when tested through Postman
For your issue try a look at this one How do I POST urlencoded form data with $http in AngularJS? - you probably need to transform your request in order to sent in via $http service with the required content type.

What is type of data angular sending?

What is type of data angular sending? I use laravel + angular. I`m trying, but this script return 405 error. Method not allowed.
.controller('adminCtrl', function( $scope, $http ){
$scope.collection = [];
$scope.newData = [];
$scope.newrecord = function() {
$scope.collection.push($scope.newData);
$http({
url: '/newrecord',
method: "POST",
data: $.param($scope.collection),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data){
console.log(data);
})
}
})
You are getting 405 - Method not Allowed because the server you are sending your request does not have POST it the white list of methods allowed to be used to perform requests to that given API.
It's not an angularJS issue, it's a server configuration issue.
$http sends data as json.
You do not need to serialize params using "$.param", data is plain javascript object, which is send to your REST endpoint.
So attach just "$scope.collection) and do not set Content Type manually, it is json by default.
POST can be send also with convenience method.
$http.post('/someUrl', data, config).then(successCallback, errorCallback);

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.

Resources