I am completely new to WCF world.
I am trying to make POST call to WCF Service method and passing json data to it.
My code snippet is as below:
Ajax POST call:
function PostJSON() {
var form_data = {
"req_limitmsg_header": {
"brch_code": "784",
"rqst_id": "00129538",
"tnx_id": "20150200008695",
"inp_user_id": "UAT01",
"inp_dttm": "20150311183413",
"Func_code": "6010 ",
"idms_tnx_type_code": "N",
"Spaces": "12",
"prod_ref_id": "12"
} ,
"req_limitmsg_detail": [
{
"jrn_exc_cur_code": "0000",
"jrn_exc_act_no": "019000090000",
"sign of exc_acpt_amt": "+",
"exc_acpt_amt": "0000000000000000",
"sign of jrn_exc_amt": "+",
"jrn_exc_amt": "0000000001500000"
},
{
"jrn_exc_cur_code": "0000",
"jrn_exc_act_no": "019000090000",
"sign of exc_acpt_amt": "+",
"exc_acpt_amt": "0000000000000000",
"sign of jrn_exc_amt": "+",
"jrn_exc_amt": "0000000001500000"
}
]
};
$.ajax({
cache: 'false',
async: 'false',
type: 'POST',
url: "http://localhost:10647/JsonTest.svc/Rest/RequestLimitCheckService",
data: JSON.stringify(form_data),
contentType: "application/json; charset=utf-8",
dataType: 'json',
crossDomain: true,
processData: true,
success: function (data, status, jqXHR) {
if(data != null)
{
alert("NOT NULL");
alert(data.toString());
}
else
{
alert("NULL");
alert(data.toString());
alert(status.toString());
}
},
error: function (response) {
alert(response);
}
});
}
WCF Method:
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "RequestLimitCheckService")]
public string RequestLimitCheck(string form_data)
{
//do somethig
}
WCF Interface
[OperationContract]
string RequestLimitCheck(string form_data);
What is happening is I am always getting null string. I tried specifying query string parameter style as well but it's of no use. It is only working fine if I specify class to accept the json data.
Please let me know if I am doing anything wrong or missing something.
Remove JSON.stringify(form_data) and use simply form_data instead and try again. Also you do need to specify the type of request format you are expecting.
Related
Following is a contract in IService interface
[OperationContract]
[WebInvoke(UriTemplate = "/service1/Add", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
MyClass AddProperty(MyClass propertyArgs);
Following is my implementation
public MyClass AddProperty(MyClass args)
{
//I always get args null here
}
Following is my code to call above service
var settings = {
"async": true,
"crossDomain": true,
"url": "url",
"method": "POST",
"headers": {
"content-type": "application/json",
},
"processData": false,
"data": '{"userid": 342507,"name": "markand"}'
}
$.ajax(settings).done(function (response) {
console.log(response);
});
The problem is that my service is enable to collect the data sent from ajax. I get my args parameter always null.
Try this and let me know if it works. I'm using it and it is working fine for me
var data = {"userid": 342507,"name": "markand"};
$.ajax({
contentType: "application/json; charset=utf-8",
data: JSONstring.make(data),
dataType: "json",
type: "POST",
url: "url",
async: true,
timeout: 90000,
success: function (items) {
//Your success handling here
},
error: function (obj, timeout, message) {
//Your error handling here
}
});
Editted: your setting must have only the data to be parsed in this example
i am new to WCF and have created a WCFand named it as CategoryMasterWCF.svc file with iCategoryMasterWCF.cs having following codes
namespace InfraERP.WebServices
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ICategoryMasterWCF" in both code and config file together.
[ServiceContract]
public interface ICategoryMasterWCF
{
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat= WebMessageFormat.Json)]
string DoWork();
[OperationContract]
[WebGet]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json)]
string sting(int id);
}
}
and CategoryMasterWCF.svc.cs having code as follows
namespace InfraERP.WebServices
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "CategoryMasterWCF" in code, svc and config file together.
[AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Allowed)]
public class CategoryMasterWCF : ICategoryMasterWCF
{
public string DoWork()
{
return "Hello, It Worked! ";
}
public string sting(int id)
{
string _sting = "Number is " +id.ToString();
return _sting;
}
}
}
and then i have added code in my aspx as follows
$.ajax({
type: "POST",
url: '../WebServices/CategoryMasterWCF.svc/sting',
contentType: "application/json; charset=UTF-8; charset-uf8",
data: {id:"1"},
processData: true,
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + "---" + errorThrown);
}
});
The error coming is "unsupported media type".
i am not an expert in WCF or Asp.net. And i have searched a lot in the web and also in stackoverflow, and tested with the changes provided, but found no good result. Currently i have not made any changes in the web config. please help me to find a way out.
Did you try removing contentType and dataType from ajax call?
What's the [WebGet] attribute doing above the sting method? You're supposed to use either one of those (WebGet for Http GET and WebInvoke for the rest with POST as default). Since you're doing a POST request in your website you can remove it.
Also convert the data you are sending to a JSON string:
$.ajax({
type: "POST",
url: '../WebServices/CategoryMasterWCF.svc/sting',
contentType: "application/json; charset=UTF-8; charset-uf8",
data: JSON.stringify({id:"1"}),
processData: true,
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + "---" + errorThrown);
}
});
I have a asmx webservice which has a webmethod that I'm calling it via jquery ajax and it returns a string, I want to read and edit cookies from this method, I know that I can read the cookie like this:
HttpContext.Current.Request.Cookie["cookie_name"];
but when I'm trying to change the value of this cookie, this doesn't work:
HttpContext.Current.Response.Cookie["cookie_name"].Value = "some_value";
so let's say this is my function:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(EnableSession = true)]
public string myMethod()
{
//...some actions
if(HttpContext.Current.Response.Cookie["cookie_name"] != null)
{
HttpContext.Current.Response.Cookie["cookie_name"].Value = "some_value";
}
return "";
}
and here is my ajax call
$.ajax({
type: "POST",
url: "/route-to/myMethod",
data: JSON.stringify({ }),
contentType: "application/json",
charset: "utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
}
});
What's exactly is wrong in this code?
I know there are a few questions out there but I've tried a lot of them and I'm still not able to even get my script to make it to the server. Here is what I currently have:
Javascript
function UpdateSessionUser(user)
{
if (user != null)
{
var targetPage = "http://" + document.location.host + "/Sitefinity/Services/Sandbox/SessionUsers.asmx/UpdateSessionUser";
var dataText = { "jsonUser" : JSON.stringify(user) };
try
{
$.ajax({
type: "POST",
url: targetPage,
data: dataText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
alert(response.d);
return true;
},
failure: function (msg)
{
alert(msg);
return false;
}
});
}
catch (err)
{
alert(err);
}
}
}
Example of user object
Object
BaseID: "fe85149c-71f2-4c61-b7c6-a00300e2f84e"
HasChanged: true
IsReferralReceived: false
IsReferralRequired: true
IsSeatApproved: true
Name: "Miles"
ReferralFromUser: null
ReferralFromUserID: null
ReferralReceivedBy: null
ReferralReceivedByUserID: null
ReferralReceivedOn: "/Date(-62135578800000)/"
RegisteredOn: "1330281960000"
SeatApprovedBy: null
SeatApprovedByUserID: null
SeatApprovedOn: "/Date(-62135578800000)/"
SeatNumber: "2"
SessionID: "d0773d5e-aeeb-4b9c-b606-0a564d6c5845"
UserID: "6af2fd9e-b4b6-4f5a-8e9c-fe7ec154d4e5"
__type: "SandboxClassRegistration.SessionUserField.ClientSessionUser"
C#
[WebMethod]
public bool UpdateSessionUser(object jsonUser)
{
return SessionUserHelper.UpdateSessionUser(new ClientSessionUser(jsonUser));
}
Why does my JSON call never make it to the server? I've put a break point at the very beginning of the function (before the return) just so I can look at the jsonUser object parameter but it never makes it there.
All I get in return is this error:
POST http://localhost:60877/Sitefinity/Services/Sandbox/SessionUsers.asmx/UpdateSessionUser 500 (Internal Server Error)
--- UPDATE
Here is the final result (I had to "stringify" the object and then the final dataText being sent). The webservice method was unchanged
function CallWebServiceToUpdateSessionUser(target, user)
{
var dataText = { "jsonUser": JSON.stringify(user) };
$.ajax({
type: "POST",
url: target,
data: JSON.stringify(dataText),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
alert(response.d);
return true;
},
failure: function (msg)
{
alert(msg);
return false;
}
});
}
I don't how much would help:
try change this
var dataText = { "jsonUser" : JSON.stringify(user) };
to
var dataText = JSON.stringify({ "jsonUser" : user });
I think you need to mark your service method as JASON enabled.
[WebMethod]
[ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
public bool UpdateSessionUser(object jsonUser)
{
return SessionUserHelper.UpdateSessionUser(new ClientSessionUser(jsonUser));
}
I realize this question was answered a while ago, but I had similar problem, and would like to provide some details on why OP's solution works
I assume the web service expects a string, which it will Deserialize and work with
In this case, calling JSON.stringify({"jsonUser": user}) does not convert user object to string, which will cause problems on the server.
When you call JSON.stringify({"jsonUser": JSON.stringify(user)}), your user oblect is converted to string with all quotes properly escaped.
Hope this helps someone in the future.
Here's the fiddle to illustrate http://jsfiddle.net/dvwCg/2/ :
HTML
<h1>webservice breaks</h1>
<span id="s1"></span>
<h1>webservice works</h1>
<span id="s2"></span>
JS
var jsonObject = {"a":1, "b":[{"x":"test", "y":12}, {"x":"test2", "y":120}]};
$("#s1").text(JSON.stringify({"d" : jsonObject}));
$("#s2").text(JSON.stringify({"d" : JSON.stringify(jsonObject)}));
p.s.
https://stackoverflow.com/a/6323528/3661 has a lot of useful info as well.
I have a strange error where my jquery ajax request doesn't submit all the parameters.
$.ajax({
url: "/ajax/doAssignTask",
type: 'GET',
contentType: "application/json",
data: {
"just_a_task": just_a_task,
"fb_post_date": fb_post_date,
"task_fb_postId": task_fb_postId,
"sedia_task_guid": sedia_task_guid,
"itemGuid": itemGuid,
"itemType": itemType,
"taskName": taskName,
"assignedToUserGuid": assignedToUserGuid,
"taskDescription": taskDescription
},
success: function(data, status) {
//success code
},
error: function(xhr, desc, err) {
//error code
}
});
But using firebug (and debugging) I can see that only these variables are posted:
assignedToUserGuid
itemGuid
itemType
just_a_task
taskDescription
taskName
It's missing fb_post_date, task_fb_postId, and sedia_task_guid
I have no idea what would cause it to post only some items and not others? Anyone know?
Data is sent to asp.net controller that returns jsonresult (hence the contentType)
Any help is appreciated. Thanks!
You could try some things such as:
See if all variables have values
Try to remove the "_" from the variable's names
What you should to to help with coding and debug is move the JSON data to a variable... ie, then you can easily see what is inside the variable before posting
var myData = {
just_a_task: just_a_task,
fb_post_date: fb_post_date,
task_fb_postId: task_fb_postId,
sedia_task_guid: sedia_task_guid,
itemGuid: itemGuid,
itemType: itemType,
taskName: taskName,
assignedToUserGuid: assignedToUserGuid,
taskDescription: taskDescription
};
var jsonData = $.toJSON(myData);
$.ajax({
url: "/ajax/doAssignTask",
type: "GET",
contentType: "application/json",
dataType: "json",
data: jsonData,
success: function(data, status) {
//success code
},
error: function(xhr, desc, err) {
//error code
}
});
Though I dont have time to run the code, could be the speech marks in the JSON. That should be out as its native JavaScript
Check for special characters in your data values (, { } [ ] " '). You have to escape those characters for JSON to work.
Hope this helps.
in the interest of a sanity check, try adding a beforeSend to your options and ensure the values are being sent and go from there....
e.g.
.ajax({
beforeSend: function (xhr) {
// this==the options for this ajax request
if(! fb_post_date || !task_fb_postId || ! sedia_task_guid){
alert("BORKED!");
}
},
....