posting data in $http post request - angularjs

I'm trying to post data from my form to an API on another domain. Request body comes back empty.
When I go to devtools, payload shows as [object Object]
I tried setting different headers like 'Content-Type' : 'application/json' or undefined but had no luck
CODE
$scope.form
{
"name":"Test",
"email":"test#test.com",
"companyName":"company",
"companySize":"6 - 10 employees",
"manageTimeOff":true
}
submit function
$scope.submitForm = function () {
$scope.success = false;
$scope.loading = true;
$http({
url: url,
method: 'POST',
data: $scope.form,
withCredentials: false,
headers: { "Content-Type": "application/x-www-form-urlencoded" },
transformRequest: angular.identity
}).then(function (response) {
console.log(response);
$scope.loading = false;
if (response.data.Error) {
$scope.success = false;
swal("Something's gone wrong ☹", response.data.Error, "error")
} else {
$scope.success = true;
swal({
title: "Form Submitted",
text: "We look forward to speaking with you soon!",
icon: "success"
});
$scope.resetForm();
}
});
}

Content type x-www-form-urlencoded is obsolete. Design backends to use content type application/json which the AngularJS framework supports by default.
$http({
url: url,
method: 'POST',
data: $scope.form,
withCredentials: false,
̶h̶e̶a̶d̶e̶r̶s̶:̶ ̶{̶ ̶"̶C̶o̶n̶t̶e̶n̶t̶-̶T̶y̶p̶e̶"̶:̶ ̶"̶a̶p̶p̶l̶i̶c̶a̶t̶i̶o̶n̶/̶x̶-̶w̶w̶w̶-̶f̶o̶r̶m̶-̶u̶r̶l̶e̶n̶c̶o̶d̶e̶d̶"̶ ̶}̶,̶
̶t̶r̶a̶n̶s̶f̶o̶r̶m̶R̶e̶q̶u̶e̶s̶t̶:̶ ̶a̶n̶g̶u̶l̶a̶r̶.̶i̶d̶e̶n̶t̶i̶t̶y̶
}).then(function (response) {
//...
});

Related

Angular: then execute before http call complete

When I call addCategory, it suppose to add my new category and then call _initAdminController() to go back to my main page and refresh the data there. But what is happening is getcourselist and getsubjectlist in initAdminController are somehow running first and then addCategory runs last. Do you know what can cause this? Am I using then correctly?
function _initAdminController() {
$scope.pageIndex = "adminTab";
console.log("reloading data");
$http({
method : 'GET',
url : 'http://testserver.com:8082/getSubjectListService'
}).then(function successCallback(response) {
$scope.updatedSubjects = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
$http({
method : 'GET',
url : 'http://testserver.hughes.com:8082/getCategoryListService'
}).then(function successCallback(response) {
$scope.categories = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
}
$scope.addCategory= function(){
var name = $scope.addCategoryData.name;
var desc = $scope.addCategoryData.description;
$http({
method : 'POST',
url : 'http://testserver.com:8082/addCategoryService',
withCredentials: true,
cache: true,
headers : { 'Content-Type': 'application/json' },
data : {
name: name,
description: desc
}
}).then(_initAdminController(), function errorCallback(response) {
console.log(response.statusText);
});
}
Also when I use then for http get, that case is working correctly. The http get finishes first and then my scope variable get updated.
And lastly before I tried the following code and in that case, successCallback doesn't run at all. So does this mean then only works for GET?
$http({
method : 'POST',
url : 'http://testserver.com:8082/addCategoryService',
withCredentials: true,
cache: true,
headers : {
'Content-Type': 'application/json'
},
data : {
name: name,
description: desc
}
}).then(
function successCallback(response) {
_initAdminController()
},
function errorCallback(response) {
console.log(response.statusText);
}
);
The code:
}).then(_initAdminController(), ...);
Should be:
}).then(_initAdminController, ...);

Angularjs http post request - params are not reaching to server

I am trying to create post request with angularjs. This is my code for adding an supplier to server.
SupplierService.addNewSupplier = function(supplier) {
alert (supplier.name);
alert (supplier.mobile);
var Indata = {'name': supplier.name, 'mobile': supplier.mobile};
//var Indata = {'product': $scope.product, 'product2': $scope.product2 };
var req = {
url: SupplierURL,
method: 'POST',
params: Indata,
headers: {'Content-Type': 'application/json'}
};
//$http.post(SupplierURL, Indata)
$http(req)
.then(function(success){
console.log(success);
//SupplierList.push({id: data, name: supplier.name, mobile: supplier.mobile});
supplier.name = "";
supplier.mobile = "";
},function (error){
console.log(error);
alert ('Supplier add error.');
});
};
After making the request, callback is coming to error part and in console log i can see.
{error: true, message: "Failed to create supplier. Please try again", name: null, mobile: null}
Why name and mobile is not reaching to server. Same request works fine with postman(api testing tool). So i don't thing there can be anu issue in server side code. Any help will be appreciated.
From the $http documentation you can clearly see request parameters:
https://docs.angularjs.org/api/ng/service/$http
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
So, in your case you need to switch params with data:
var req = {
url: SupplierURL,
method: 'POST',
data: Indata,
headers: {'Content-Type': 'application/json'}
};

Pass parameter to webmethod $http post

I need to pass parameter to the webmethod below. I have value Param which need to be passed to webmethod.
var param='test'
$http({
method:"POST",
url:'/sites/Demo/_layouts/15/demo/Demo.aspx/mywebmethod',
data: JSON,
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data)
{
$scope.Jobject = data.data.d;
});
Please advise.
You may pass params key for parameters or data key form body data which is not available in GET method
var params = {
name: 'This is parameter query'
}
var data = {
name: 'This is body data'
}
$http({
method: 'POST',
url: '/sites/Demo/_layouts/15/demo/Demo.aspx/mywebmethod',
data: data,
params: params
}).then(function successCallback(response) {
$scope.Jobject = response.data.d;
}, function errorCallback(response) {
console.log(response);
});
or simply use
$http.post('/sites/Demo/_layouts/15/demo/Demo.aspx/mywebmethod', data).then(function successCallback(response) {
$scope.Jobject = response.data.d;
}, function errorCallback(response) {
console.log(response);
});
You can use $http.post
$http.post('/sites/Demo/_layouts/15/demo/Demo.aspx/mywebmethod', params)
For more details check official documentation
$http({
method:"POST",
url:'/sites/Demo/_layouts/15/demo/Demo.aspx/mywebmethod',
data: JSON,
headers: {
'Content-Type': 'application/json'
},
params: {name: param}
})
.then(function(data)
{
$scope.Jobject = data.data.d;
});
assuming you want to send that params string as a name

null with receipt data in angular $http

This is my code:
$scope.doLogin = function() {
$http({
method: "POST",
url: "http://localhost:8000/api/v1/user/user_signin",
data: { username: $scope.user.username, password: $scope.user.password },
headers: { 'Content-Type': 'application/json' },
responseType:'json'
}).success(function (data) {
console.log('data success');
console.log(JSON.stringify(data));
})
.error(function(data, status, headers,config){
console.log('data error');
});
};
Consol says:
data success
null
What I do wrong?
P.S.: API request is correct - I checked it in postman.
You set responseType to 'json' make sure that your server side is also sending the response compatible to your format 'json'.
Or simply remove the response type check if it works

POST http://URL 422 (Unprocessable Entity)

I am trying to make a post request through Angular. My code looks as follows,
Javascript Code looks like:
GET:
$scope.getRecord = function() {
debugger;
$http({
method: 'GET',
url: 'SomeURL'
}).then(function(response) {
debugger;
$scope.mainEntity = response.data.anEntity;
}, function(error) {
$scope.content = "something went wrong"
});
};
Post:
$scope.save = function() {
debugger;
var body = JSON.stringify({
"xyzaa": $scope.value.xyzaa || "One fielfd of its",
"xyzbb": $scope.value.xyzbb || One fielfd of its,
"xyzcc": $scope.value.xyzcc || "One fielfd of its",
"xyzaaa": $scope.value.xyzaaa || "One fielfd of its"
});
var request = {
method: 'POST',
url: 'Some URL',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
data: body
};
$http(request).then(function (result) {
debugger;
$scope.getRecord();
}, function (error) {
debugger;
console.log(error)
alert("error")
})
};
Well, I can see that the post request returns the data that I have done in a JSON Format, yet am receiving the error:
POST http://localhost:xyz/xyz/a (Unprocessable Entity)
Object {data: Object, status: 422, config: Object, statusText: "Unprocessable Entity"}.
I can see that data that am being posting is getting in the data key and I can see the data that I have passed, yet I get this error and it doesnt change in the api

Resources