GetData(...) method was OK, but SetSimple(...) method throwing error 400.
Javascript:
$.ajax(url,
{
type: action,
timeout: 3000,
data: { value: 123 },
contentType: "application/json; charset=utf-8",
//dataType: "json",
success: function (data, textStatus, jqXHR) {
displayInfo("success: "+data);
},
error: function(jqXHR, textStatus, errorThrown ) {
displayInfo("error: "+errorThrown+" "+textStatus);
}
}
);
C#:
[WebGet(RequestFormat = WebMessageFormat.Json)]
string GetData(int value);
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST")]
string SetSimple(int value);
To run/test it I have the service opened in a browser, then my test page with the javascript in another browser. (And dataType: "json" doesn't seem to help.)
And the fiddler response shows "The server encountered an error processing the request. See server logs for more details", but I don't see anything in the Event Logs. Anyone see if/what I'm doing wrong?
You should be transform your JavaScript object into string.
JSON.stringify(data)
Then on your example
$.ajax (url,
{
type: action,
timeout: 3000,
data: JSON.stringify({ value: 123 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
displayInfo("success: "+data);
},
error: function(jqXHR, textStatus, errorThrown ) {
displayInfo("error: "+errorThrown+" "+textStatus);
}
}
);
Your ajax request is setting the "data" property to { value: 123 }. You need to pass the appropriate object to the SetObject method which is CompositeType. The ajax request looks like you're using it as a utility function so just pass data as a parameter so the ajax request would be:
var makeAjaxCall = function(url, action, data) {
$.ajax(url,
{
type: action,
timeout: 3000,
data: data,
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
displayInfo("success: "+data);
},
error: function(jqXHR, textStatus, errorThrown ) {
displayInfo("error: "+errorThrown+" "+textStatus);
}
}
);
}
Related
I have the following ajax function
var jsonId = JSON.stringify(sortedIDs);
$.ajax({
type: "POST",
data: { ids: jsonId },
datatype: "json",
contentType: "application/json; charset=utf-8",
url: "/Intranet/Dev/TestSortTable.aspx/GetData",
success: function (msg) {
alert(msg.d + "success");
},
error: function (response) {
alert("an error has occured");
}
});
And the following method in the code behind page
[WebMethod]
public static string GetData(string[] data)
{
return "this is the string from the code behind file";
}
The error I am getting is a 500 internal server error. If I add .cs to the TestSortTable.aspx I get a 404 not found error. This is the first time I have implemented an Ajax function and I am at a loss as to what I have done wrong. I should add that sortedIDs is defined elsewhere.
You're not sending the parameters as JSON. You're converting sortedIDs to JSON, but being wrapped into an object that gets sent as URL-encoded data. You need to do:
var json = JSON.stringify({data: sortedIDs);
$.ajax({
type: "POST",
data: json,
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Intranet/Dev/TestSortTable.aspx/GetData",
success: function (msg) {
alert(msg.d + "success");
},
error: function (response) {
alert("an error has occured");
}
});
Also, datatype: should be dataType:
I want to post data to server with ajax call but i am getting an error.
var userdata = {};
userdata["Name"] = "Saran";
var DTO = { 'userdata': userdata };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/update",
data: JSON.stringify(DTO),
datatype: "json",
success: function (result) {
//do something
alert("SUCCESS = " + result);
console.log(result);
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
console.log("error: " + errorthrown);
}
});//end of $.ajax()
I have created a function in Default.aspx.cs and tried to access that function with the above call.
[WebMethod]
public static string update(string userdata)
{
return "Posted";
}
Error :
POST http://localhost:33762/Default.aspx/update 401 Unauthorized 52ms
Message "Authentication failed." StackTrace null ExceptionType
"System.InvalidOperationException"
Firstly, you have to set/update to settings.AutoRedirectMode = RedirectMode.Off; in App_Start/RouteConfig.cs.
Secondly, your ajax payload is not structured properly to make the appropriate call to the update method. See updates below:
var DTO = { 'userdata': 'Saran' };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/update",
data: JSON.stringify(DTO),
datatype: "json",
success: function (result) {
//do something
alert("SUCCESS = " + result.d);
console.log(result);
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
console.log("error: " + errorthrown);
}
});//end of $.ajax()
When I try to send json JSON.stringify(coords); or above code I get error message but I try when the data is empty like data:{} the code works correctly. How can I solve this problem?
$.ajax({
type: "POST",
data: {"yagiz":"aabb"},
dataType: 'json',
url: url,
crossDomain:true,
async: false,
contentType: "application/json; charset=utf-8",
success: function (response) {
$("#Content").text(response.d);
console.log(response.d);
},
failure: function (response) {
alert(response.d);
console.log(response.d);
}
});
Web Method
[System.Web.Services.WebMethod]
public static string GetLocationPolygon(string location)
{
return location;
}
You can debug on server side as 500 internal error raised at server side only. You can catch and log the exact exception.
try this code
$.ajax({
type: "POST",
data: JSON.stringify({"location":"aabb"}), //Change here
dataType: 'json',
url: url,
crossDomain:true,
async: false,
contentType: "application/json; charset=utf-8",
success: function (response) {
$("#Content").text(response.d);
console.log(response.d);
},
failure: function (response) {
alert(response.d);
console.log(response.d);
}
});
My AJAX code is below. In this i cannot get the response from server side C# code. But there is no issues with my server side code ( I have checked it by debugging ). From server side i am returning string to this ajax.
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]' +"provider/GetState",
contentType: 'application/json',
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
}
});
Server side code is below
public string GetState(string CountryId)
{
int i= Convert.ToInt32(CountryId);
var Details = objUserAccount.SP_Getstate(i).ToList();
if(Details.Count>0)
{
return "Success";
}
else
{
return "False";
}
}
Add datatype in your ajax request like this, if datatype is not matched with received data from server then the ajax error will call instead of success
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]'+ NSSCTProvider/GetState",
contentType: 'application/json',
dataType: "json",
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
},
error: function(data){
alert("Error occured");
}
});
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]'+ NSSCTProvider/GetState",
contentType: 'application/json',
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
},
error: function(data){
alert("Error occured");
}
});
Either one of the success or failure call back will be initiated if the request is made from this snippet. Might be a server issue, most probably. And make sure that this is the code snippet getting executed. Happens to me all the time.
Using .NET framework 3.5.
I can't figure what's happening? My Get WCF services seem to be fine using the same approach.
Not sure, what's missing?
WCF:
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public void PutInventory(int caseId, DateTime dateReceived, string tamisCaseNo, string oarNo, string tin, string taxPdr, int oarTypeCd, string idrsOrgAssigned, string idrsTeAssigned, DateTime dateRequestComp, int tasCriteriaCd, string tasExpidateCd, DateTime dateEntered, string remarks)
{
InventoryDAL.PutInventory(caseId, dateReceived, tamisCaseNo, oarNo, tin, taxPdr, oarTypeCd, idrsOrgAssigned, idrsTeAssigned, dateRequestComp, tasCriteriaCd, tasExpidateCd, dateEntered, remarks);
}
Ajax call my webform:
$.ajax({
url: "Services/IVOOARInventoryService.svc/PutInventory",
type: 'POST',
cache: false,
dataType: 'json',
data: ({
caseId: '<%=Request.QueryString["id"]%>', dateReceived: $("#dateEntered").val(), tamisCaseNo: $("#tamisCaseNo").val(), oarNo: $("#OARNo").val(), tin:$("#tin").val(), taxPdr: $("#taxPeriod").val(), oarTypeCd: $("#oarType").val(), idrsOrgAssigned: $("#idrsOrgAssigned").val(), idrsTeAssigned: $("#idrsTeAssigned").val(), dateRequestComp: $("#dateRequestComp").val(), tasCriteriaCd: $("#tasCriteriaComp").val(), tasExpidateCd:$("#tasExpediateCd").val(), dateEntered: $("#dateEntered").val(), remarks: $("#remarks").val()
}),
error: function (jqXHR, textStatus, errorThrown) {
$("div#spinner").fadeOut("slow");
alert(errorThrown);
},
success: function (json) {
$("div#spinner").fadeOut("slow");
}
});
My error:
{"ExceptionDetail":{"HelpLink":null,"InnerException":null,"Message":"The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.
Just figured it out, needed to use "JSON.stringify"
Example:
data: JSON.stringify({
caseId: "18"
...etc..
}),
http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/
Set the content type to application/json
$.ajax({
url: "Services/IVOOARInventoryService.svc/PutInventory",
type: 'POST',
cache: false,
dataType: 'json',
contentType:"application/json",
data: ({
caseId: '<%=Request.QueryString["id"]%>', dateReceived: $("#dateEntered").val(), tamisCaseNo: $("#tamisCaseNo").val(), oarNo: $("#OARNo").val(), tin:$("#tin").val(), taxPdr: $("#taxPeriod").val(), oarTypeCd: $("#oarType").val(), idrsOrgAssigned: $("#idrsOrgAssigned").val(), idrsTeAssigned: $("#idrsTeAssigned").val(), dateRequestComp: $("#dateRequestComp").val(), tasCriteriaCd: $("#tasCriteriaComp").val(), tasExpidateCd:$("#tasExpediateCd").val(), dateEntered: $("#dateEntered").val(), remarks: $("#remarks").val()
}),
error: function (jqXHR, textStatus, errorThrown) {
$("div#spinner").fadeOut("slow");
alert(errorThrown);
},
success: function (json) {
$("div#spinner").fadeOut("slow");
}
});