I am using $http to POST an angularjs variable, I do receive the JSON equivalent in servlet's doPost method. When I write a JSON in the response from the servlet, $http.success(data, status, header, config) is called. But when I assign 'data' to an angularjs variable, no value get's assigned to the variable. Tried using JSON.parse(data) but of no use. Following is the code snippet.
AngularJS
$scope.result = {
title: "",
subject: "",
summary: "",
body: "",
extra: ""
};
$http.post(url, JSON.stringify(obj)).
success(function(data, status, headers, config){
$scope.result = JSON.parse(data);
console.log("data: " + data);
console.log("status: " + status);
console.log("headers: " + headers);
console.log("config: " + config);
})
.error(function(data, status, headers, config){
$scope.result = JSON.parse(data);
console.log("data: " + data);
console.log("status: " + status);
console.log("headers: " + headers);
console.log("config: " + config);
});
Console output on receiving the response is as follows
data: [object Object]
status: 200
headers: function (name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
}
config: [object Object]
Following is the code snippet from the servlet.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("doPost called");
response.getWriter().write("{"title":"Transaction Status","subject":"Congratulations!!","summary":"Successfully received your request, below is your Transaction ID","body":"5a85fc3b303d47dca6514b707442f2cd","extra":"Please save this transaction ID for future reference"}");
}
I am not able to obtain the JSON sent from doPost() method in angularjs success function. Is it the correct way of doing it? Angularjs automatically converts the received JSON to javascript object type, so I must be able to assign 'data' straight to $scope.result.
It will be great if someone can please point me in right direction.
data
is an object containing a propertydata
. That property holds what you want. You may want to renamedata
to something likeresponse
. If you do, you could assignresponse.data
(without usingJSON.parse()
– Sprottenwels Jul 23 '14 at 8:49console.dir(data)
and add the response to your question please – Sprottenwels Jul 23 '14 at 8:58