AJAX Callback using POST method - asp.net

I require some assistance. I am using jQuery to cause an ajax callback:
function TestingCallback(controlId) {
if (controlId == 'drpControl') {
var options = {
type: "POST",
url: "Main.aspx",
data: { drpControl: $(".drpControl").val() },
//contentType: "application/json; charset=utf-8",
//cache: false,
success: function (data) {
},
complete: function (jqXHR, status) {
formData = $("#form1").serialize();
window.location = "Main.aspx?" + formData;
ShowLoadingBar();
return false;
}
};
var resp = $.ajax(options);
}
}
And the backend I get the data like so:
Request.Form["drpControl"], which works well.
But as soon as I add this line to the callback options : contentType: "application/json; charset=utf-8",, I get a value of null for Request.Form["drpControl"].
Please assist on how to overcome this.
Thanks in advance
Might I just add that I am trying to cause a postback but keep all control values, hence this line :
formData = $("#form1").serialize();
window.location = "Main.aspx?" + formData;
But after a second postback (on change of drpControl) field values gets cleared, I am assuming this has to do with IE not being able to cater for a long querystring, I have tested it in Chrome and it works perfect, but not IE, and I need it to work for IE 8.Any suggestions?

in content type just add this
contentType: "application/json"
Designating the encoding is somewhat redundant for JSON, since the default encoding for JSON is UTF-8. So in this case the receiving server apparently is happy knowing that it's dealing with JSON and assumes that the encoding is UTF-8 by default, that's why it works with or without the header.
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')-
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it'll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.
Note sure but pass data like this
data: "{'drpControl' : " + $(".drpControl").val()+ "}",

Related

Post object of array to api in ReactJs

When I have post the Array of object via API to the server than data is not pass properly to the api.
My object have 2 property one is GUID type and one is string type, at the server side my each object return as null data.
In console posted data is this
posted Params data is this
I am beginner in the reactJs so can any one help me how I can save object or array or any array via API
You may need to use JSON.stringify(dataToPost) in the reactjs to convert the data to string before posting to server. I hope the server is RESTful API
I have make changes in my post method and now my Ajax post method this.
export function postJson(url, data, success, error = nothing) {
const settings = {
url,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
async: true,
success: onSuccess(success, error),
error,
}
if (data) {
settings.data = JSON.stringify(data)
}
$.ajax(settings)
}

Why is an OPTIONS request sent to the server?

I use a simple jQuery.ajax method:
$.ajax({
type: "GET",
url: serviceUrl + '/GetAgentsGroupNameById',
contentType: "application/json; charset=utf-8",
data: { id: agentsGroupId },
async: false,
success: function (data) {
agentsGroupName = data["d"];
},
error: function (request, message) {
agentsGroupName = '';
}
});
The 'Get' request is sent and I get a well-formed json response from the server.
The problem is that I see in the developer tools that another request is generated to the same URL, with request method: OPTIONS, with an empty response, and I see an error:
OPTIONS http://localhost:1004/MobileService.asmx/GetSubscribedAgentsByUserId?userId=27 500 (Internal Server Error)
What is this OPTIONS request?
Why does it happen?
P.S. I mentioned that if I delete contentType: "application/json; charset=utf-8" (and add dataType: json or jsonp), no OPTIONS request is generated, but I don't get a well-formed json as a response (I get kinda xml document)
BTW: the service is asp.net c#:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string GetAgentsGroupNameById(int id)
PLEASE LET ME KNOW IF YOU NEED ANY FURTHER DETAILS ABOUT THE REQUEST OR THE RESPONSE
Thanks from advance!!!
The OPTIONS request is because of the Cross origin resource sharing. It is basically the web browser asking the destination server whether it allows cross domain resource sharing.
In short, you cannot make json requests to a different domain than the domain that the page is being served from.
If you are only doing GET requests, you may want to look at JSONP which solves this issue. However, it only works with GET requests.
There have been a lot of questions on this, and there is a details answer here
Try switching your $.ajax 'Type' to use the POST verb rather than GET.

ASP.NET webservice responds with Internal Server Error (500) to post and get requests

The webservice code is simple:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void receiveOrder(string json) {
Context.Response.Write("ok");
}
And the jquery calling the webservice is as follows:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'http://localhost:50730/GingerWeb.asmx/receiveOrder',
data: 'test', //JSON.stringify(webOrder),
dataType: "text",
success: function(data){
if(data === "ok")
orderPlaced();
}
});
And yet the chrome console reads in provocative red:
500 (Internal Server Error)
The problem is that ASMX web-service need to find all input parameters in the request. If at least one input parameter will be not found in the request to the server the web service failed with the status code 500 (Internal Server Error).
The reason is that you send the data in the wrong way. The name of the input parameter of the web method is json (see void receiveOrder(string json)). So the data option of the $.ajax should be in the form
data: JSON.stringify({json: webOrder})
if you use type: "POST" instead of data: JSON.stringify(webOrder) which you tried before. In the case in the body of the POST request will be json=theVlue instead of just theValue.
If you would use type: "GET" the format of data parameter should be changed to
data: {json: JSON.stringify(webOrder)}
The value of the dataType should be 'json'. After the changes the $.ajax should work.
Moreover I would recommend you to use relative paths in the url option. I mean to use '/GingerWeb.asmx/receiveOrder' instead of 'http://localhost:50730/GingerWeb.asmx/receiveOrder'. It will save you from same origin policy errors.
Hello Oleg: Your explanation is simple and to the point. I had a similar problem which your explanation solved. I am providing code snippet to help 'searchers' understand what I was facing and how the above helped solve. In short I am issuing a simple jquery (.ajax) from a aspx page. I have created a webservice that gets some data from backend (cache/db) and return's the same in json format.
JS CODE:
var parameters = "{'pageName':'" + sPage + "'}"
var request = $.ajax({
type: "POST",
url: "/NotificationWebService.asmx/GetNotification",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
ASP.NET Code Behind for Web Service
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetNotification(string pageName)
{
JavaScriptSerializer js = new JavaScriptSerializer();
Notification ns = NotificationCache.GetActiveNotificationForPage(pageName);
if (ns != null)
{
NotificationJSData nJSData = new NotificationJSData();
nJSData.Code = ns.Code;
nJSData.displayFreq = (short)ns.DisplayFreq;
nJSData.expiryDate = ns.ToDateStr;
return js.Serialize(nJSData);
}
return null;
}
It is ABSOLUTELY necessary to ensure that you match 'pageName' variable name specified in web service code with what is sent in your data parameter of the ajax request. I had them different and changed it to be the same, after spending hours, I finally found the right solution, thanks to this post. Also, in my case I am only passing a single "name:value" pair so I didn't even have to use some json De-serialization function to get the value, pageName above gives me only the value.

In ASP.NET with JQuery, how would you define and handle exceptional conditions

I use $.ajax to call a .asmx to get JSON data back. The server side process will meet some exceptional conditions which will give back to client error response for displaying error message.
How would you design the error hanlding mechanism? I mean what would you make server side retrun and let client handle the error?
Thanks.
If it's just an error message (a string), then you can just return that string and set the status to 500 so jQuery recognizes it's not a successful request. Then just use your error handler (or a global .ajaxError() handler for all requests) to do what you want with that message.
For example a simple way to handle all errors like this (instead of per-$.ajax() call) would be:
$(document).ajaxError(function(e, xhr) {
alert("There was an error, server responded with: " + xhr.responseText);
});
ther's an error handler in jquery just like the success function, you need to handle it:
function CallWebService(ParentPage) {
$.ajax({
type: "POST",
url: "../Admission/AdmissionService.asmx/LoadLocations",
data: "{'ParentPage':'" + ParentPage + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.innerHospitalCensusdiv').html(data.d);
BindSelectLocation();
},**error: function(ex){
//handle error here
}**
});
}

Problem retrieving XML data from an ASP.NET Web service

I am trying to call a Web service to retrieve some XML data from a database. The Ajax call works fine if I use a static file e.g. like this:
$.ajax({
type: "GET",
url: "test2.xml",
data: buildXMLDataRequestObject(),
dataType: "xml",
success: getXMLDataSucceeded,
error: getXMLDataFailed
});
but fails when I try to call the Web service e.g. like this:
$.ajax({
type: "POST",
url: "Services/CheckOutService.svc/GetXMLData",
data: buildXMLDataRequestObject(),
dataType: "xml",
success: getXMLDataSucceeded,
error: getXMLDataFailed
});
The error I get is:
"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."
The GetXMLData method looks like this:
// Interface
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string GetXMLData(XMLDataRequest request);
...
// Implementation
public string GetXMLData(XMLDataRequest request)
{
request.ShopperId = ShopperId;
return checkOutManager.GetXMLData(request);
}
The GetXMLData method has been configured to return XML and the Ajax call has its datatype set as XML so I'm very confused as to what is causing the error.
EDIT: If I alter the $.ajax() call slightly so that the contentType is specified I get this error:
The data at the root level is invalid.
Line 1, position 1.
I've tried contentType: "text/xml" and contentType: "application/xml" and both give the same error.
EDIT: Yesterday (Aug 30th) I noticed that the service call would succeed if I omitted the data parameter of the ajax call. I guess there is something about the JSON object that is causing a problem. For now I have implemented this functionality on the server side of the application but I do intend to revisit this when I get some time.
My first guess would be that the content type was wrong. What do you see when you look at the stream using Fiddler or similar?

Resources