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.
});
Related
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");
});
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'};
}
}
I have an $http POST call in AngularJS that won't show the server response if the request was bad.
myFactory.create = function(formData) {
deferred = $q.defer()
$http({method: 'POST', url: url, responseType: 'json', data: formData})
.then(function(data) {
deferred.resolve(data);
}, function(response, status, headers, config) {
deferred.reject(response);
});
return deferred.promise;
};
When I submit incorrect data, the API responds with a 400 - Bad Request. If I look at the response in Chrome Developer tools, there is a plain text message: "Vertical is not correct." However, that message is not in the response on the $http error callback.
I can get everything else (status, headers and config) but my response data is null.
Successful POSTs are processed correctly so I know that the function generally works.
Any idea why I would be able to see the response in Chrome but not able to access it via $http?
You can refactor to this:
myFactory.create = function(formData) {
var url = 'api/create';
return $http({
method: 'POST',
url: url,
responseType: 'json', //Are you sure that it is returning a json??
data: formData
});
};
Then check the return of the promise like this wherever you wish to call it,
myFactory.create().then(
function(data){
console.dir(data);
},function(response, status, headers, config) {
console.dir(response);
});
This should work and you should see the data on the logs.
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
I'm just starting out with Angular.js and I'm trying to figure out how to set up a factory that will show cached data and replace it with data retrieved from a REST service once it is received.
To test this out, I'm just hard-coding the "cached" data. Once the data is received, I want the $scope.directory variable to be updated with the latest data received from the server. I can either get it
Here's my factory code:
app.factory('directoryFactory', function ($http) {
var factory = {};
factory.directory = [{name: "Test", ext: "123"},{name: 'Bob', ext: "234"}];
init();
function init() {
$http({
method: 'GET',
url: '{restapiURL}'
})
.success(function (data, status, headers, config) {
factory.directory=data;
})
.error(function (data, status, headers, config) {
console.log('directory fail');
});
}
}
My Controller has the following code:
$scope.directory = directoryFactory.directory;
In my view, I use ng-repeat to list out all the people and their extensions.
I'd like the view to be updated once the data is received. What's the correct way to watch for factory data changes?
Your $scope.directory is promise that contains 2 handlers on success and on failure. Since $http is asynchronous, you don't know when response should come but "promise" will notify you about in case if you use then()
Here is example of POST but its the same flow:
factory:
myModule.factory('ajax_post', ['$http', function(_http) {
var path = 'src/php/data.ajax.php';
return{
init: function(jsonData){
var _promise= _http.post(path,
jsonData
,{
headers: {
'SOAPActions': 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems'
}
}
);
return _promise;
}
}
}]);
In controller:
var _promise= ajax_post.init(jsonData);
_promise.then(function (result) {
//do something with your result
},
function (error) {
alert(error.message);
}
);