jquery Ajax responsetext "There was an error processing the request" - c#

I am getting this error "There was an error processing the request" in the UAT environment. In my local, the code seems to be working fine.
This line Utility.WriteLogEvent("TestService", strMessage); is writing directly to db. Either way if this line fails or not, I should still be able to recieve a message coming from the server since it is properly handled.
But since I don't receive any response from the server, that means my webmethod is not reachable.
Given that the code below works, is there anything that I need to set in the web.config to make this work? Or anywhere I can start inspecting on the IIS that could give me some clues?
Thanks.
$('#lnkTest').click(function () {
alert('Click event is firing!');
$.ajax({
type: "POST",
url: "/_layouts/ServiceForm.aspx/TestService",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response.d && response.d.length > 0) {
alert(response.d);
}
},
error: function (xhr, err) {
alert('responseText:' + xhr.responseText);
}
});
});
Here is my c# web method
[WebMethod]
public static string TestService()
{
string strMessage = string.Empty;
try
{
strMessage = "The service is running.";
Utility.WriteLogEvent("TestService", strMessage);
}
catch (Exception ex)
{
strMessage = "TestService fail.";
}
return strMessage;
}

For others who might come across the same error while calling a WebMethod with parameters.
Ensure that none of the arguments are empty as that also throws the same error without a proper reason. Provide a solution to prevent empty arguments from being passed to the Method on the client side. Perhaps an if statement.

I have resolved the issue. This is due to a dll deployed in the application server and it was blocked by the installed antivirus.

Related

jQuery POST passing null string on server (ASP.NET)

I have an ASP.NET application sending data through AJAX to a handler withing my application. This works as it should when debugging locally, but as soon as I deploy the solution to the server, the handler only receives an empty string. I tried fiddling around with contentType and dataType, but without luck.
Here is my code so far.
aspx of the sending page, while "myData" is a simple string:
$.ajax({
type: "POST",
url: "handlers/changeRiskGroup.ashx",
data: myData,
// tried all those content/dataTypes without any luck
//contentType: "text/plain",
//dataType: "text",
//contentType: "application/json; charset=utf-8",
//dataType: "json",
error: function (xhr, status, error) {
console.log(xhr.responseText);
},
success: function (msg) {
console.log(msg);
}
});
.ashx.cs of the receiving handler:
public void ProcessRequest(HttpContext context) {
//string data = new StreamReader(context.Request.InputStream).ReadToEnd();
var data = String.Empty;
context.Request.InputStream.Position = 0;
using(var inputStream = new StreamReader(context.Request.InputStream)) {
data = inputStream.ReadToEnd();
}
if (data != "") {
// doing something with my data here.
// this is never reached while on the server, but works fine locally!
} else {
context.Response.Write("Please supply data to the risk group service!");
}
}
public bool IsReusable {
get {
return false;
}
}
}
The data variable in the .ashx.cs file is filled when debugging locally, but always "" on the server. I have no clue why.
var para={};
para.myData="abcd"
$.ajax({
type: "POST",
url: "handlers/changeRiskGroup.ashx",
data: para,
error: function (xhr, status, error) {
console.log(xhr.responseText);
},
success: function (msg) {
console.log(msg);
}
});
from server side
string myData=contect.Request.Form["myData"].toString();
Easy, just took me ~20 hours to figure out. Found the answer here: Web service returns "301 error moved permanently" in production environment
In short, I created a blank page within my project to ensure no plugins etc were interfering with the jQuery execution. Further, I created a very simple mask to submit certain data to the handler URL. Within this mask I varied different ways to POST data, when I tried implementing the POST as a [WebMethod] I finally got a clue, as the response was "301 moved permanently" from the WebMethod. Therefore I could start investigating and found out that my server was lowercasing the urls, obviously jQuery/HTTP does not like that.
I hope this post helps others struggling with similar problems.

How to get data from Soap service by jquery?

I want to get data from Webservice( Soap), but it not successfull. My service herehttp://icafe.ipos.vn/WSUitility/evsServiceUtility.svc?wsdl
I use jquery to request to service, code below
var soap = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<Test xmlns=''>" +
"</Test>" +
"</soap:Body>" +
"</soap:Envelope>";
$.ajax({
url: 'http://icafe.ipos.vn/WSUitility/evsServiceUtility.svc?wsdl',
method: 'post',
data: soap,
contentType: "text/xml",
dataType: "xml",
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction", "urn:evsServiceUtility/Test1");
},
crossDomain: true,
success: function(SOAPResponse) {
alert('ok');
},
error: function(SOAPResponse) {
alert('no ok');
}
});
And my service:
public string Test()
{
try
{
return "Successfull!";
}
catch (Exception ex)
{
return ex.Message;
}
}
I spended many many times to search and try many solutions but it not working.
Can anyone help me?
I suppose your data type can be XML, not a problem there. Question is, how do you encode your data or parameters? Perhaps check the response in the POST request in the console of your browser.
I picked up a few things in c# to enable this automatically which is nicely documented here:
http://encosia.com/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/
Then one thing left to do was to JSON.stringify() the data. So bhRequest is a json object right?
... and then cross browser you'll have to implement json2.js:
https://github.com/douglascrockford/JSON-js
I don't see where your var named soap is being used. It looks like it should be the "data: " that's being sent to the SOAP service, but there's something called bhRequest there instead.
Also make sure you're allowing Phonegap access to your remote server with
<access subdomains="true" origin="*" />
in your config.xml. When you get things working you can make it more restrictive by limiting it to your icafe.ipos.vn domain.

jquery Ajax error function is not triggered

Below is my function (1st Code piece), when I run below function, it goes into to my code through my handler and in my code it throws exception (2nd Code piece), after exception is catched, it goes back to my handler and get's inside the catch area, and finally turns back to javascript success function, but error it doesn't run the error part.
BenefitOperations.performBenefitOperation = function(data) {
$.ajax({
type: "POST",
url: "BenefitOperation.axd",
data: JSON.stringify(data.BenefitOperationJson),
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: function() { PageMask.show(); },
success: function(response) {
if (response.Success == true)
performPostBack();
else
window.alert(Res.BenefitOperationFailure);
},
error: function(e, x, y) { window.alert(Res.BenefitOperationError + y); } }); }
This is my function
else
{
throw new ApplicationException(string.Format("Benefit operation type {0} for benefit type {1} is not registered", Enum.GetName(typeof(EmployeeBenefitData.BenefitOperationType), parameters.OperationTypeID), Enum.GetName(typeof(EmployeeBenefitData.BenefitTypeEnum), parameters.BenefitTypeID)));
}
this is my handler's catch
catch
{
jsonOutput = JsonConvert.SerializeObject(new
{
Success = false
});
}
finally
{
context.Response.Clear();
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.ContentType = "application/json";
context.Response.Write(jsonOutput);
}
The error callback of $.ajax() doesn't get called in your code because there is no error. error means there was an issue retrieving the response, eg. a 500 error from the server.
In your code you're catching the ApplicationException yourself and returning JSON. If you'd prefer to use the error handler, raise the exception and don't catch it in your C# code - however it should be noted your current code is a better method.
Rory is right,
just set HTTP 500 status code when you hit error / Exception or operation faild.
you can set HTTP 500 status code like...
context.Response.StatusCode = 200;

$.Ajax POST, accessing return data

I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.
On my .cs file I have the following Webmethod
[WebMethod]
public static string IsJobEditable(int jobid)
{
try
{
string isEditable = "false";
JobsBLL jbl = new JobsBLL();
int jobStatusId = jbl.GetJobStatusId(jobid);
if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
{
isEditable = "true";
}
return isEditable;
}
catch (Exception ex)
{
throw ex;
}
}
This function in this case will ALWAYS return TRUE as a string.
On Aspx page I have the following
$(function () {
$.ajax({
type: "POST",
url: "Coordination.aspx/IsJobEditable",
data: "{jobid:" + jobid + "}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (result) {
alert(result);
// This is written out in the alert {"d":"true"}
// I want this in a variable as a string
// so I can do a check on it before I do some other actions
// The format is not a String so i cannot split on it to
// retrieve the "true" part.
},
error: function (err, result) { alert(err); }
});
});
As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.
So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).
Use result.d to get your string.
See this site for an explanation of the .d issue when calling .ajax from ASP.NET: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
try alert(result.d);
You can easily retrieve the "true" part like this:
alert(result.d);
The reason the object is wrapped in the "d" json object is security. You can read about it for example here.
According to two articles I found, I think you want to specify "DataType" as json not as text (since you're expecting a content-type of json to be returned). That may be your issue, though i don't have a sample project in front of me to test on. Your result is also probably result.d as outlined in those same articles.
This solved it:
$(function () {
$.ajax({
type: "POST",
url: "Coordination.aspx/IsJobEditable",
data: "{jobid:" + jobid + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
//I finally got the data string i wanted
var resultAsString = result.d;
},
error: function (err, result) { alert(err); }
});
});
So 2 things were done to solve this. I had to change the dataType to "json" and I used the result.d to retrieve my data.
What threw me off was the lack of intellisens on the result object. But the .d (data) property however solved it.
Thanks you to all who contributed to this answer.

Ajax post error

I want to post data to a web service with ajax. there is my ajax code:
function Looping() {
var Grid = document.getElementById("<%= gvHastalar.ClientID %>");
var Row;
var Cell;
if (Grid.rows.length > 2) {
for (i = 1; i < Grid.rows.length - 1; i++) {
Row = Grid.rows[i];
Cell = Row.cells[3];
alert(Cell.innerHTML);
var html = $.ajax(
{
type: "POST",
url: "http://localhost:7753/HastaTahlilUyariServisi.asmx/f_HastaninAktarilacakAlislabTestleri",
data: "{_sTcKimlikNo:" + Cell.innerHTML + ",_iKlinikKodu:18001,_bAy:12,_iYil:2009}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: alert('success'),
error: alert('error')
}
).responseText;
Row.style.backgroundColor = "#D3EFD1";
}
}
}
And my webservice function's code is here:
[WebMethod]
[SoapHeader("_ticket", Direction = SoapHeaderDirection.In)]//SoapHeaderDirection.Out
public DataSet f_HastaninAlisLabTahlilleri(string _sTcKimlikNo, int _iKlinikKodu, byte _bAy, int _iYil)
{
try
{
string QSelect =
#"SELECT * FROM [V_EUCLID_SONUC]
WHERE MONTH(KAYITTARIHI) = " + _bAy + #"
AND YEAR(KAYITTARIHI) = " + _iYil +
AND TCKIMLIKNO = '" + _sTcKimlikNo + #"'";
return dbA.ExecuteDataSet(CommandType.Text, QSelect);
}
catch (Exception ex)
{
throw (ex);
}
}
There is a break point on function which is in the web service but debug never go that break point. I pasted webservice's url from browser but may be url is wrong. And when i run project, i have 3 alert.
First Cell's text its normal.Second alert is success and the last alert is error. I want to send parameters to f_HastaninAlisLabTahlilleri and user return dataset. How can i do this?
Thanks in advance
Here are a few remarks about your code:
success and error are callback functions, they should be defined like this:
success: function(data) { alert('success'); },
error: function(XMLHttpRequest, textStatus, errorThrown) { alert('error'); }
ASMX web services use SOAP by default unless you decorate them with ScriptServiceAttribute in which case JSON could be used to invoke a method. It is not clear from your code if the web service is decorated with this attribute.
When you pass parameters, you need to encode them, use JSON. stringify instead of concatenating strings:
data: JSON.stringify({_sTcKimlikNo: Cell.innerHTML,
_iKlinikKodu: 18001,
_bAy: 12,_iYil: 2009});
Use FireBug to inspect network AJAX requests and server responses and post them on StackOverflow to facilitate debugging.
You cannot put a break-point in the web-service code i.e. even the IDE would not let u debug the web-service code.... it is an old legacy the VS.Net IDE has since its inception... lets see if it is resolved in VS 2010.
The url that you have specified in the JQuery script is not equal to the name of the function in c# code. Isn't it the point. *f_HastaninAktarilacakAlislabTestleri* in url and *f_HastaninAlisLabTahlilleri* in c# code. Some reasons for such a problem can be wrong url or deference between argument list of client request and argument list of the server side method or action.

Categories