I have a problem with posting data to the WP Rest API in combination with my Angular webApp. My first guess is that I am not posting the data in the right format.
My function to post the data is as follows: (some data is static for test purposes only)
$scope.submitComment = function () {
var d = new Date();
commentForm = [
{
'author_email': $scope.email,
'author_name': $scope.name,
'author_url': 'http://www.domain.com',
'content': $scope.comment,
'date': '2015-11-29T20:10:36',
'date_gmt': '2015-11-29T19:10:36',
'karma': '',
'parent': 0,
'post': $scope.postID,
'status': 'approved',
'type': 'comment'
}
];
$http({
method: 'POST',
url: 'http://www.domain.com/wp-json/wp/v2/comments?post=' + $scope.postID,
data: commentForm
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
});
$scope.showCommentForm = false;
$scope.showCommentButton = true;
};
When I log commentForm, all the properties are set. But none of them are inserted into the database. What am I doing wrong? The response of the $http Post is a 201, so it seems successful.
Related
I think it is not a big problem but I can't find any solution for this. Using Angular I want to display item details from database. I have my server side code that is searching for ID and returning Json. Then in Angular controller I get the data, single record. But I can't display any informations about this. It only works when I use ng-repeat but that's not the case. There is no point to use ng-repeat when I have just one single record.
//
It shouldn't be something like this?
$scope.item = { name: 'jack', city: 'sydney' };
And in my view
{{item.name}}
But with my single record from database it's not working. Do you have any idea what is wrong here? Or maybe I'm missing something? Here is my code
ASP.NET MVC Controller:
public JsonResult GetGame(int id, string gameName)
{
var getById = GetGameById(id, gameName);
if (getById != null)
{
using (KeyGameContext dbx = new KeyGameContext())
{
dbx.Configuration.ProxyCreationEnabled = false;
var getGame = dbx.Games.Find(id);
return Json(getGame, JsonRequestBehavior.AllowGet);
}
}
else
{
return Json(null);
}
}
public Game GetGameById(int gid, string gName)
{
return db.Games.Find(gid);
}
AngularJS code:
$http({
url: '/Genre/GetGame',
params: {
id: $routeParams.id,
gameName: $routeParams.gameName
},
method: 'get'
}).then(function (data) {
$scope.getGame = data;
console.log(data);
});
And here is some informations about this record from the console
Yea this throws people off when they first start using $http. Try this
$http({
url: '/Genre/GetGame',
params: {
id: $routeParams.id,
gameName: $routeParams.gameName
},
method: 'get'
}).then(function (data) {
$scope.getGame = data.data;
console.log(data);
});
What gets passed into your "then" promise function is the response object, which contains information about the http request in addition to your data. The actual data object is stored at .data
So I usually write mine as
$http({
url: '/Genre/GetGame',
params: {
id: $routeParams.id,
gameName: $routeParams.gameName
},
method: 'get'
}).then(function (response) {
$scope.getGame = response.data;
console.log(data);
});
just replace your code
$scope.getGame = data;
to
$scope.getGame = data.data;
"Happy Coding"
Hey I want to change the data before sending it with ngResource (build FormData object). I do everything as in the examples that I found, however I can't make them work. Here is my code:
My controller where I set the data and try to send them:
var vm = this;
vm.application = new Application();
vm.application.title = 'Test title';
Application.save({}, vm.application, function(){
});
My service:
function application(ApiBaseUrl, $resource) {
var actions = {
'save': {
metod: 'POST',
url: ApiBaseUrl + "/applications",
headers: { 'Content-Type': false },
transformRequest: function (data) {
console.log(data); //Returns 'undefined'
return data;
}
}
};
return $resource(ApiBaseUrl + "applications/:id", {}, actions);
}
In the function transformRequest data object is always marked as 'undefined'. Am I doing something wrong? Is there a better way to edit the data before sending it?
The problem was I had
metod: 'POST'
when I should have used:
method: 'POST'
I'm trying to create an html/angularjs form that submits data to my webserver. The page is loading the controller because it does execute the submit function. I get an "ReferenceError: formData is not defined" error when I reference formData data. I thought this was the proper way to initialize members of a controller.
var app = angular.module('messagingForm', []);
app.controller('messagingController', function($scope, $http) {
$scope.formData = {
userName: "bob",
email: "bob#bob.com",
subject: "why",
message: "why not?"
};
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(sendContact) {
$scope.submitted = true;
console.log('validating data');
if (sendContact.$valid) {
console.log('sending data');
$http({
method: 'post',
url: 'email.php',
data: {
'name': formData.userName,
'email': formData.email,
'subject': formData.subject,
'message': formData.message
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} //set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
});
} else {
console.log('validating not good');
alert('failed');
}
}
});
I'm unclear how I initialize a member variable I guess. what is the right way to do this?
Matt.
Try with this:
Change:
data: {
'name': formData.userName,
'email': formData.email,
'subject': formData.subject,
'message': formData.message
},
to
data: {
'name': $scope.formData.userName,
'email': $scope.formData.email,
'subject': $scope.formData.subject,
'message': $scope.formData.message
},
Then:
var app = angular.module('messagingForm', []);
app.controller('messagingController', function($scope, $http) {
$scope.formData = {
userName: "bob",
email: "bob#bob.com",
subject: "why",
message: "why not?"
};
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(sendContact) {
$scope.submitted = true;
console.log('validating data');
if (sendContact.$valid) {
console.log('sending data');
$http({
method: 'post',
url: 'email.php',
data: {
'name': $scope.formData.userName,
'email': $scope.formData.email,
'subject': $scope.formData.subject,
'message': $scope.formData.message
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} //set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
});
} else {
console.log('validating not good');
alert('failed');
}
}
});
Because in your code, «formaData» it doesn't exist in the context. You might try also declaring a local variable, something like this:
var formData = {
userName: "bob",
email: "bob#bob.com",
subject: "why",
message: "why not?"
};
Example:
var app = angular.module('messagingForm', []);
app.controller('messagingController', function ($scope, $http) {
var formData = {
userName: "bob",
email: "bob#bob.com",
subject: "why",
message: "why not?"
};
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(sendContact) {
$scope.submitted = true;
console.log('validating data');
if (sendContact.$valid) {
console.log('sending data');
$http({
method : 'post',
url : 'email.php',
data : {
'name': formData.userName,
'email': formData.email,
'subject': formData.subject,
'message': formData.message
},
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
});
} else {
console.log('validating not good');
alert('failed');
}
}
});
You could also create the formData object as a constant and then explicitly pass it in to the controller.
var app = angular.module('messagingForm', []).constant("formData", {
'userName': 'bob',
'email': 'bob#bob.com',
'subject': 'why',
'message': 'why not?'
});
app.controller('messagingController', function($scope, $http, formData) {
Rest of you code here...
It just makes it a little clearer and easier to test.
I am trying to login to a website with the following request:
var request = require('request');
var options = {
method: 'POST',
url: 'https://server/EnterpriseController',
params: {a: 1},
form: "actionType=authenticateUser&reqObj=[null,username,password,null,1]",
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
withCredentials: true,
rejectUnauthorized: false
};
request(options,
function (error, response, body, data) {
if (request.method === 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var post = qs.parse(body);
});
}
console.log(body);
}
);
I am always getting an error. I think the form is wrong but I have the same login on an angularjs site without any error. I don't understand why the login works on angularjs site but not in nodejs.
)]}',
{"login_err": true, "resp": [null,null,null,1]
}
I missed the cookie:/ And the Formdata should be an Object.
I'm trying to send the post request to server with post data
it's sent the request to the server, but not in right format
request url like /rest/api/modifyuser/?currentPassword=admin&newPassword=admin
it's like GET request - (may be this is problem)
I'm new to angularjs . please share idea to solve this problem
Here is my code
In controller
var currentPass = "admin";
var newPass = "admin";
var confirmPass = "admin";
var authToken = "abcdef";
User.changePassword(currentPass, newPass, confirmPass, authToken, function(response) {
angular.forEach(response, function (item) {
alert("resp"+ item);
});
});
In services
UIAppResource.factory('User', function($resource) {
return {
changePassword: function(currentPass, newPass, confirmPass, authtoken, callback) {
var Resq = $resource(baseURL + "modifyuser", {}, {
'query': {
method: 'POST',
params: {
'currentPassword': currentPass,
'newPassword': newPass,
'confirmPassword': confirmPass
},
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'X-Internal-Auth-Token': authtoken
},
isArray: false
}
});
Resq.query(callback);
}
};
});
Thanks in advance
I dont want to say you are doing it all wrong.. but you are def. abusing things. The default way to POST something with ng-resource is to use save. Second, the default way to send data is to instantiate a $resource factory with the data you want. See _resource below. We pass the data we want, and it will automagically convert it and if its a POST send it in the body, or in the case of a GET it will turn into query parameters.
UIAppResource.factory('User', function($resource) {
return {
changePassword: function(currentPass,
newPass,
confirmPass,
authtoken,
callback
) {
var Resq = $resource(baseURL + "modifyuser", {}, {
'save': {
method: 'POST',
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'X-Internal-Auth-Token': authtoken
}
}
});
var _resource = new Resq({
'currentPassword': currentPass,
'newPassword': newPass,
'confirmPassword': confirmPass
});
_resource.$save(callback);
}
};
});