Angular JS POST request not sending data - json

I am trying to send an JSON object to my webservice which is expecting JSON in the request data.
This my POST call from angularJS
$http({method: 'POST',
url: 'update.htm',
data: $.param($scope.cover),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function (data) {
// handle
});
Value for cover object
$scope.cover = {id:1, bean:{id:2}}
Iam getting 500 (InvalidPropertyException: Invalid property 'bean[id]' of bean class [BookBean]: Property referenced in indexed property path 'bean[id]' is neither an array nor a List nor a Map;)
In network, it is sending in this way
bean[id]:1
I think it should send like
bean.id:1
How to reslove this issue. Thanks in advance

Looks like the data is getting to the server and is causing an error there. There's a possible duplicate question that's been answered here - Post Nested Object to Spring MVC controller using JSON

Try posting your data like:
$http({method: 'POST',
url: 'update.htm',
data: $scope.cover,
}).success(function (data) {
// handle
});

Related

how to process json post request with nodejs http (no express framework)? [duplicate]

Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

Request Media Type[application/json] Error! Request Body is not JSON format issue for Extjs Ajax request

I am using Extjs 5.1.3. I have post request with params as-
{"root":{"countryId":"458","ruleId":"3386","ruleName":"Test1 \\","ruleType":"CELL_STORE","opType":"DETAILS"}}
I am creating ajax request as-
Ext.Ajax.request({
method: 'POST',
url: appurl.fetchRuleDetails,
params: win.jsonData,
callback: function(option, success, response){
})
})
From server side, response is coming as-
{
"rules":[
{
"countryId":"458",
"ruleId":"3386",
"ruleName":"Test1 \\",
"ruleType":"CELL_STORE",
"ruleParts":[
{
"seq":"1",
"attrId":"6",
"attrName":"Store Type",
"op":"=",
"val":"dsafdaf",
"charType":"GLOBAL_CHAR"
}
]
}
],
"Status":{
"StatusFlag":true,
"StatusCode":"SUCCESS",
"StatusMessage":"SUCCESS"
}
}
But in Ajax request's callback function, we are receiving response.responseText as-
Request Media Type[application/json] Error! Request Body is not JSON format.
My guess is like issue is because of rulename value as "Test1 \".
So can someone please help me whats missing.
The error message is not an ExtJS error message. If you receive an ExtJS error related to invalid JSON, it will look like this:
Uncaught Error: You're trying to decode an invalid JSON String: TestTest
My best guess is that the error message comes from the server, because it expects you to send your request as JSON. Right now you are sending it as FormData. To send the request as JSON, you have to put your object in the jsonData config and leave the params config undefined:
Ext.Ajax.request({
method: 'POST',
url: appurl.fetchRuleDetails,
jsonData: win.jsonData,
callback: function(option, success, response){
})
})
For future questions regarding server-client communication, please keep in mind that you should first check in your browser network tab what you send to the server and what the response from the server really is.

How can i pass an object and a string to webservice using post request using angularjs

Am very new to angularjs and i need to post data to a web service, the service accepts two parameters, one is List of object and the other is securityToken,
Here is my code,
$scope.saveCompany=function(){
// alert("Save Company!!!");
var Companies={
Code: 'testMartin',
Name: 'company1',
CompanyType : 'Tenant',
email : 'test#yaoo.com',
Fax : 4235353,
ParentID : 1
};
$http({
url:'http://localhost/masters/smstools.svc/json/SaveComapnies',
dataType: 'json',
method: 'POST',
data: $.param(Companies),
headers: {
"Content-Type": "text/json",
}
}).success(function(response){
alert ("Success");
}).error(function(error){
alert ("Save company!");
});
how can i pass the security token with the companies object as a separate paramenter. my service accepts the parameters like this,
public List<CompanyProfile> Save(List<CompanyProfile> CompanyList,string securityToken)
Since this is a rest call you only have 3 places were you can pass parameters data:
With Post and it will be part of the body, it seems this is what is your first parameter is occupying now.
With Get and you add the parameter to the URL /json/SaveComapnies/mySecParam or by queryString like /json/SaveComapnies?sec=mySecParam but this is not secure nor recommended for security settings.
With header from angular Post:
**headers: {
"Content-Type": "text/json",
"mySecVar": "mySecParamValue"
}**
Server side version:
public List<CompanyProfile> Save(List<CompanyProfile> CompanyList){
WebOperationContext current = WebOperationContext.Current;
WebHeaderCollection headers = current.IncomingRequest.Headers;
if (headers["mySecVar"] != null){
// do something
}
}
You can read more about it here:
How to read HTTP request headers in a WCF web service?
Can you share more information in your Backend?
If it is actually a REST Backend I would rather use an angular $resource
https://docs.angularjs.org/api/ngResource
If you want to pass json object and string as post Parameter you should stick to the $http docs
https://docs.angularjs.org/api/ng/service/$http
In the post example you can pass both params in:
$http.post('/yourEndpoint', {jsonObj:yourCompaniesObj, secKey:yourSecretToken})....(sucess etc)
Typing from my cell - if you need more code examples just tell

Posting parameters in one URL and getting JSON from another URL

Am working in jQueryMobile and PhoneGap.
Currently am facing an issue that; For get the details in JSON format ; I post parameters into an URL (URL1) and I get the JSON response from another URL (URL2)
Currently i cant access the JSON data from the second URL.
My code is ;
function proceed_payment(){
var cardholder_= $('#input_Cardholder_name_').val();
var card_num_ = $('#input_CreditCard_').val();
var payment_ =$('#card_type_').val();
var cvv2_=$('#input_cvv2_').val();
var url;
url='https://www.sample.com/json/save_pament.php?json=1&rcg_mobile=2&reserv_num='+reservation_number+'&callback='+reservation_carcompany+'&cardholder='+cardholder_+'&payment='+payment_+'&card_num='+card_num_+'&card_cvv2='+cvv2_+'&card_expire_mon='+expire_month+'&card_expire_year='+expire_year+'&org_deposit='+sCarDeposit+'&org_cur='+currency+'&mond='+company_Show_mond+''
$.ajax({
url:url,
data:'',
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
crossDomain:true,
cache: false,
async:false,
success:function(data)
{
alert(data.Status);
$.mobile.changePage( "#reservation_status", {reverse: false, changeHash: true});
event.preventDefault();
},
error: OnError
});
};
Here I Post the parameters to URL1 : - https://www.sample.com/json/save_pament.php?
and get the JSON result in URL2 : https:// www.sample.com /result_bank_eup6.php?app=1
But My problem is i cant access the result from URL2.
Is there any method for solve this?
Please HELP :-(
Ullas Mohan V.
As per our discussion in comments and the error you mentioned
( [object Object]-parseerror-SyntaxError: Unexpected token < ).
The issue is related to web service/server side
Web service is not sending the desired response.
So client side/$ajax is not able to parse it.
You can check the actual response using Google Chrome's Advance REST Client.
To resolve this issue, you should contact the company
which is developing server side for you.

Returning JSON with web api controller MVC

I am trying to convert a regular old controller I was using to an API controller and am having a little bit of difficulty. What these series of functions do is, in the jQuery, it iterates over a file containing all the usernames of employees and for each username it makes a call to the PopulateEmployee method in my webapi controller which should return JSON and then populate a results div.
When manually navigating to
..domain../staffinformation/populateemployee/employeeusername
I get the error
This XML file does not appear to have any style information associated with it. The
document tree is shown below.
<Error>
<Message>
The requested resource does not support http method 'GET'.
</Message>
</Error>
Please note that the div it will be populating is a partial view in an Umbraco CMS page and I don't think that is the problem but if you guys think differently please tell me.
There has to be something I am missing either with webAPI routing or something else.
Thanks for your help.
Here's the codez.
Please notice that this method has the HttpPost tag
public class StaffInformationController : ApiController
{
[System.Web.Http.ActionName("PopulateEmployee")]
[System.Web.Http.HttpPost]
public StaffListing PopulateEmployee(string id)
{
//do error checking on input
StaffListing staffListing = new StaffListing(id);
//populate other fields
return staffListing;
}
}
The routing set up for the api controller
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
The jQuery call specifying use of 'POST', please forgive the trickiness of the recursive call in this function.
function getEmployeeObjectByIndex() {
$.ajax({
url: $('#root').val() + '/api/StaffInformation/PopulateEmployee',
type: 'POST',
async: true,
contentType: 'application/json, charset=utf-8',
data: JSON.stringify({ 'username': lines[i] }),
success: function (staffObject) {
if (!(staffObject.Name == undefined)) {
buildHtmlStrings(staffObject);
}
i++;
getEmployeeObjectByIndex(); //recursive call
}
});
}
manually navigating to that address throws the error because, when manually navigating you are doing a GET (and your method only allows POSTs).
You should fire up Fiddler and watch the ajax POST request and response to see how the server is responding / your request is being made
Jquery ------> web api
Web API has one property i.e. CONTENT NEGOTIATION means you send any data and accept any data as you want.
$.ajax({
contentType: 'application/json, charset=utf-8',
// this is sending your data of datatype json to server, here you send any type of data
accept: 'application/json',
//this is receiving/getting data form server to client...
// SO HERE YOU GET JSON DATA AS YOU WANT only mention which data of datatype u want...
//if you sending xml and you want json so only write accept as json it get automatically converted into your required datatype..by MediaTypeFormatter
});