Rama Lingam Rama Lingam - 1 month ago 7
JSON Question

How to solve JSON Syntax error. How to get response?

This is the UPS shipping webservices API. I am getting this error :


{"Error":{"Code":"4","Description":"JSON Syntax error"}}


AJAX Code:

<script>
var formData = { "UPSSecurity": { "UsernameToken": { "Username":"xxx.com", "Password":"xxxxx" }, "ServiceAccessToken": { "AccessLicenseNumber":"1234D567DF67" } }, "RateRequest": { "Request": { "RequestOption":"Rate", "TransactionReference": { "CustomerContext":"Test saran" } }, "Shipment": { "Shipper": { "Name":"Saravanan", "ShipperNumber":"Y72A41", "Address": { "AddressLine":["2311 York Rd"], "City":"Sebastopol", "StateProvinceCode":"CA", "PostalCode":"95473", "CountryCode":"US" } }, "ShipTo": { "Name":"ShipToName", "Address": { "AddressLine":["195 N main st"], "City":"Sebastopol", "StateProvinceCode":"CA", "PostalCode":"95472", "CountryCode":"US" } }, "ShipFrom": { "Name":"ShipFromName", "Address": { "AddressLine":"2311 York Rd", "City":"Sebastopol","StateProvinceCode":"CA", "PostalCode":"95473", "CountryCode":"US" } }, "Service": { "Code":"03", "Description":"Express" }, "Package": { "PackagingType": { "Code": "02", "Description": "Rate" }, "Dimensions": { "UnitOfMeasurement": { "Code": "IN", "Description": "inches" }, "Length": "7", "Width": "5", "Height": "2" }, "PackageWeight": { "UnitOfMeasurement": { "Code": "Lbs", "Description": "pounds" }, "Weight": "10" } }, "ShipmentRatingOptions": { "NegotiatedRatesIndicator": "" } } } };

$.ajax({
type : "POST",
url : "https://wwwcie.ups.com/rest/Rate",
crossDomain: true,
timeout : 240000,
data : formData,
dataType : 'json',
success : function(response)
{
alert("result="+response);
}
});

</script>


I don't know where I am wrong. But this request is running perfectly by "POST MAN" and "ARC" tools.
Please update answer.

Answer

You're not sending JSON; jQuery's default serialization when you give it an object is URI-encoding. To send JSON instead, convert your object to a string with JSON.stringify. You should also identify that what you're sending is JSON using contentType, so:

contentType: 'application/json',
data       : JSON.stringify(formData),