RESTful ws with form parameters in Angularjs using $resource - angularjs

Can anyone explain how can i make a post request with some values in the body of the request in Angularjs?
I tried this solution:
'getNomeServizio':
{ method: "POST",
url: basePath,
headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}
In my controller:
(new Service()).$getNomeServizio(
$.param({chiave1: valore1, chiave2: valore2'})
).then(function (data) {
...
}, function (error) {
....
})
I want to use $resource but the request doesn't pass form-parameters.
Thanks in advance.

Try this:
Service.getNomeServizio({chiave1: 'valore1', chiave2: 'valore2'}, function(){
//success
}, function(){
//error
})

Related

Post Json data from Angularjs to MVC controller

When I pass JSON data from AngularJS to MVC. I am getting below error.
Http request configuration url must be a string or a $sce trusted object. Received: {"method":"POST","url":"Home/SavePDDetails","datatype":"json","data":{"PD":{"Name":"qqq","Address":"www"}}}
MVC code:
[HttpPost]
public JsonResult SavePDDetails(PDDetailsDTO PD)
{
new PDDetailsDAL().SavePDDetails(PD);
return Json(new { Success = true, Message = "Success" });
}
AngularJS code
$scope.Click = function() {
console.log('clicked');
$http.post({
method: 'POST',
url: 'Home/SavePDDetails',
datatype: "json",
data: {
PD: $scope.PD
}
}).success(function(response) {
console.log('success');
console.log(response);
}).error(function(response) {
console.log('error');
console.log(response);
});
}
If data and url are passed as a properties of the config object, don't use the $http.post method. Simply use $http:
̶$̶h̶t̶t̶p̶.̶p̶o̶s̶t̶(̶{̶
$http({
method: 'POST',
url: 'Home/SavePDDetails',
̶d̶a̶t̶a̶t̶y̶p̶e̶:̶ ̶"̶j̶s̶o̶n̶"̶,̶
data: {
PD: $scope.PD
}
})
There is no need to stringify the data as the $http Service does that automatically.
Try as follow in your function.
Use JSON.stringify() to wrap your json
var parameter = JSON.stringify({PD: $scope.PD});
$http.post('Home/SavePDDetails', parameter).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

POSTing value from Angular to MVC controller results in null value

I am attempting to pass a value from angular to my MVC Core controller to use in a repository function as simple string. However, I've noticed that it's passing a null value to the MVC controller. I don't want to create an MVC model just to use the POSTed JSON as a string.
Function excerpt from MVC controller
[HttpPost("api/specials/GetCurrentSpecialsBySiteID")]
public ActionResult GetCurrentSpecials([FromBody] string siteID)
{
return Ok(_repo.GetAllSpecialsBySiteID(siteID));
}
$Http Angular function
$http({
method: 'POST',
url: '/api/specials/GetCurrentSpecialsBySiteID',
data: siteID,
headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})
.then(function (response) {
// success
console.log(response);
vm.Specials.push(response.data);
angular.copy(response.data, vm.Specials);
console.log(vm.Specials);
// clear the form
vm.newSpecials = {};
}, function (response) {
// failure
console.log("Error !" + response.data);
vm.errorMessage = "Failed to save subscription";
})
.finally(function () {
vm.isBusy = false;
});
In mvc controller you are passing action parameter as string.
Please check you "siteID" Type in your JS.
method: 'POST',
url: '/api/specials/GetCurrentSpecialsBySiteID',
data: siteID,
headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})
From your example it looks like you should probably be performing a GET rather than a POST, however you can adapt your methods as follows to get up and running:
[HttpPost("api/specials/GetCurrentSpecialsBySiteID")]
public ActionResult GetCurrentSpecials([FromUri] string siteID)
{
return Ok(_repo.GetAllSpecialsBySiteID(siteID));
}
And your angular function:
$http.post('/api/organisations/test?siteID=' + siteID)
.then(function (response) {
...
})
.finally(function () {
...
});
Try to pass object in $Http Angular function.
$http({
method: 'POST',
url: '/api/specials/GetCurrentSpecialsBySiteID',
data: {siteID: siteID},
headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})
.then....
For more just check $http service documentation here.

Angular $http get method does not send correct data to server

I am new at angular. I use angular.js and webapi. I have a request like below.
[HttpGet]
public RecordDTO[] GetMyFiles(UserClass usr,int uId,int fId)
{
}
my webapi call is like this. UserClass parameter is a class that has two string field(name,password). My angular code is like below.
$scope.GetMyFiles= function () {
var user = { Name:'xx',Password:'xx' };
var data = {usr:user, uId: 11, fId: 56};
$http({
url:"../api/Home/GetMyFiles",
method: 'GET',
//headers: { 'Content-Type': 'application/json' },
params: data
})
.success(function (data) {
alert("OK");
})
.error(function (data) {
alert("error");
});
};
My problem is UserClass is null. It takes uId and fId parameters, but first parameter comes null.
How can I correct this?
Thanks in advance.
As the default content-type for $http is JSON, check what your service is attending. If its JSON, you should stringify your data to pass them to your webapi :
params: JSON.stringify(data)
if you need to SEND data to the server, you should make a $http.post call. I think the problem because you are not specifiying the content-type of the header.
please try this:
$http.post('/api/Home/GetMyFiles', data , {
headers: { 'Content-Type': 'application/x-www-form-urlencoded;' }
}
).success(function(data) })
.error(function(err){});
Tell me if it works, and if you need any help let me know. Happy Coding. ;)
Change $http method from GET to POST. Also change params: data to data: data. I tried this code in my local PC and it works correctly.
Controller:
[HttpPost]
public RecordDTO[] GetMyFiles(UserClass usr, int uId, int fId )
{
}
JavaScript:
$http({
url: url,
method: 'POST',
data: data
})
.success(function (data) {
alert("OK");
})
.error(function (data) {
alert("error");
});

Get response data from Angular Factory using $resource

I try to get response data from angular service created by factory and $resource. I want to send POST request to server to create object in db and received created ID.
So I create service like this:
angular.module('sample')
.factory('Client', function ($resource) {
return $resource('api/clients/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
}
});
});
I use Client service in controller:
$scope.create = function () {
Client.save($scope.client,
function (response) {
$state.go("clientDetail", {'id' : whereIsMyId.id? })
});
};
Unfortunately, I do not know how to read data in response.
As response I just get number like "6" but this could be any JSON.
Thank you.

$http Post to php backend, but the server side gets nothing

I'm learning AngularJS, and trying to post dump data to the php backend using the coding below.
angular.module('app.customerModule', [])
.factory('customerFactory', function($scope, $http) {
return {
var customer = {customer: '1234'};
httpNewCustomer: function(callback) {
$http.post('http://domain.local/customer_new.php', )
.success(function(data) {
})
}
}
})
.controller('customerController', function($rootScope, $scope, customerFactory) {
$scope.newCustomer = function() {
customerFactory.httpNewCustomer(function(dataResponse) {
});
}
});
Unfortunately at the server side gets nothing for $_POST;
This is what the http header looks like.
I also tried with this alternative coding
httpNewCustomers: function(callback) {
var postData = {customer: '2345'};
$http({
method: 'POST',
url: 'http://domain.local/customer_new.php',
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'}
})
.success(function(data) {
})
}
This is what the http header looks like.
When I tried with jQuery using this coding, everything is just fine.
var postData = {customer: '3456'};
$.ajax({
type: 'POST',
url: 'http://domain.local/customer_new.php',
dataType: 'json',
data: postData,
success: function(data) {
// console.log(data);
}
});
Please help me config the $http to post the data to the php backend.
angular by default only supports a json request transformer. as you can see, both your angular requests have data, but they are json. You either need to change the server so it can parse json, or add a request transformer so the data is in form-encoded format.
You can read more about $http transformers here: https://docs.angularjs.org/api/ng/service/$http

Resources