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

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

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.
});

$http get dosn't work frome code but works with other rest client

I have a problem with angular $http get with Authorization header.
I tried to excute the same request with different rest client and response are the same each one.
Advanced Rest Client Chrome extension
Soap-Ui
Insomnia
I have always received the same response with 200 status code.
but when I try to make the same call from my angular application I get 403 status code and response is an OPTIONS.
where I'm wrong?
this is my code:
Config
app.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.common['Authorization']='Bearer 24ac24e6-0f9b-48b5-923f-b75986226bd9';
});
Service
app.service('DiscoveryService', function ($http) {
this.getData = function (callbackFunc) {
$http({
url: 'https://test.test/test-api/source-monitor/v1/discover',
method: 'GET',
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
console.log(response);
}).error(function (error) {
console.log(response);
});
};
});
Controller
DiscoveryService.getData(function (dataResponse) {
$scope.data = dataResponse;
});

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.

AngularJS $http.post how to set the json data into request body

I am trying to send the post request with json data to server. But seems angularJS $http.post method does not set the data into body. How can I make it set the data into body?
The remote server is implemented use asp.net webapi and will read the data from body. so I need to set the json data into request body.
How can I implement this please? Thanks.
If the request send to same site, then it works. But if I send the request to CROS server, it does not work.
In the remote backend server, I already updated the webconfig to make it support CROS call, but it still does not work.
$http.post(resourceUri, requestData)
.success(function (response) {
})
.error(function (data, status, header, config) {
});
You could build the request like this:
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': "application/json"
},
data: { test: 'test' }
}
$http(req).success(function(){...}).error(function(){...});
YOu can do it as follows
1. make a controller
2. make a add data to the call
syntax for the post call is as follows
$http.post(url, data, [config])
app.controller('controller', function ($scope, $http, $routeParams) {
$http.post('url',data.call1($routeParams.id))
.success(function (response) {
$scope.response = response;
})
.error(function (data, status, headers, config) {
});
});
var data = {
call1:
function (value) {
return {'key': value, 'key': 'some text'};
}
}

Resources