Model array values are not being submitted by $http service - angularjs

I defined an array in controller to create a array model. i.e. $scope.campaignPublish[] and I am using in my view template like
<textarea rows="" cols="" name="description" ng-model="campaignPublish['description']"> </textarea>
<input type="text" name="title" ng-model="campaignPublish['title']">
When I submit the form I'm getting all of the form values in this array i.e. $scope.campaignPublish[] but when I'm using $http.post, the data is not being submitted to server. My ajax call is
console.log($scope.campaignPublish); // Getting all form data here
$http.post('url', {'id': campaignId, 'data': $scope.campaignPublish}).then(function (response) {
//$http.post is not submitting the form data on server
});
I read some articles and got to know that it is happening because of http headers. I've already tried each and every solution posted on SO but no one exactly worked. Can anybody tell me where I am doing wrong ?

$http({
method: 'POST',
url: url,
headers: {
'Content-Type': 'text/plain'
},
data: $scope.campaignPublish
}).success(function (reply) {
console.log('sucess');
}).error(function (reply) {
console.log('error');
});

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"

Pass Data List from angularjs to webservice?

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.

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.

MongoDB is posting no data with Mongoose

I am making an app with the MEAN stack and I am having trouble POSTing data to my database. When I push the submit button, the form data is being cleared, like it is supposed to when the POST is sucessful, but when I go to the database, there is a new document with nothing in it but and id and __v.
There aren't any errors that are being thrown because there is data being posted to the DB, but not the correct data (Look at the mongodb document at the bottom of the page)
The form where the data is being posted to is this:
<input name="userName" type="String" class="form-control" id="userName" ng-model="formData.userName" placeholder="Your Name">
<input name="game" type="String" class="form-control" id="game" ng-model="formData.game" placeholder="The game?">
<input name="userPoint" type="Number" class="form-control" id="userPoint" ng-model="formData.userPoint" placeholder="Points?">
<button type="submit" class="btn btn-default" ng-click="createScore()">Submit</button>
This is createScore():
$http.post('/api/scores', $scope.formData)
.success(function(data) {
$scope.formData = {};
$scope.scores = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
This is the Mongoose model for the database:
var Score = mongoose.model("Score", {
userName: String,
game: String,
userPoint: Number
}, "score");
And this is the route for my express's "app.post()":
app.post("/api/scores", function(req, res){
Score.create({
userName:req.body.userName,
game:req.body.game,
userPoint:req.body.userPoint
}, function(err, score) {
if (err)
res.send(err);
Score.find(function(err, score) {
if (err)
res.send(err)
res.json(score);
});
});
});
When the data is POSTed, the mongodb file document looks like this:
{
"_id": {
"$oid": "54cbf3d1fbaaf10300000001"
},
"__v": 0
}
I was thinking that maybe the names were wrong (ex. userPoints and userPoint), but I made sue that they were all the same. Also, I'm new to this, so if you have any tutorials that might help concrete a topic, please feel free to share.
EDIT 1:
I did a console.log() on the node.js part where it says req.body.userName, req.body.game, etc. And in the logs, they all came out as undefined. I have been looking for a solution online, but I can't seem to find a solution. I have tried making the types in the HTML file "String" instead of "text", but that did not seem to work. Any ideas?
Ok, so I fixed my problem.
I was trying to POST as a form-data instead of a x-www-form-urlencoded.
In my core.js, I put this in the createScore method:
$http({
method : 'POST',
url : '/api/scores',
data : $.param($scope.formData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(response){
$scope.formData = {};
$scope.scores = response;
console.log(response);
});
I hope this helps someone!

Resources