Web Method not called in ajax aspx web form - asp.net

Here is my ajax request:
$("#<% =txtDiagnosisData.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: 'EMR.aspx/SearchDiagnosis',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
// response(data.d);
alert("success");
},
error: function (result) {
alert("error");
}
});
}
});
Here is my function:
[WebMethod]
public static List<string> SearchDiagnosis()
{
return new DataAccess().GetDiagnosis();
}
My method is not called from ajax, it always goes to the error part
How to solve this?

There could be an issue that you might be using Session variables inside you web method directly or indirectly.
Somewhere in the function DataAccess().GetDiagnosis();
In that case use attribute like [WebMethod(enableSession: true)] in stead of
[WebMethod]
Also try to get the error by implementing error properly like below
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
alert('Internal error: ' + jqXHR.responseText);
} else {
alert('Unexpected error.');
}
}
Ref : jQuery ajax error function and see what error exactly you are getting.

Related

unable to return model object from controller to ajax method

Method in Controller :
public JsonResult FillStateDetails(string id)
{
var st1 = dbObj.States.Find(id);
return Json(st1, JsonRequestBehavior.AllowGet);
}
Ajax call :
$(document).ready(
function () {
$("#ddl1").change(
function () {
debugger
var ddlvl = $("#ddl1").val()
$.ajax({
type: "POST",
url: '#Url.Action("FillStateDetails", "Admin")',
data :{id : ddlvl},
dataType: "JSON",
contentType: "application/json",
success: function(date) {
alert(date);
},
error: function()
{
alert("Error");
}
});
});
});
output:
unable to return the object from controller to Ajax method. error method is executing, how to return model object to ajax method.
Use xhr,status,Text parameter in your error function of ajax request.You will get exact error.If you have Parser error then remove contentType tag from ajax call.

Return bad request Erros in Web API with Json and AJAX

I want to return the error list that is in my child class and they return ok using a rest client.
I am not sure how to display the errors on the front end of my website on the forms to create a new child. I have included my create methods, controller below, any help is much appreciated
[HttpPost]// POST api/Child
public IHttpActionResult Create([FromBody]Child obj)
{
try
{
if (ModelState.IsValid)
{ // check valid state
repository.Insert(obj);
repository.Save();
return Ok(obj);
}
else // not valid request
{
return BadRequest(ModelState);
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
} // end POST Create
//MY SCRIPT FOR THE CREATE
// Called with "createForm" onSubmit
function CreateChild() {
$.ajax({
type: "POST",
contentType: "application/json",
url: rootURL,
dataType: "json",
data: formToJSONCreate(),
success: function (data, textStatus, jqXHR) {
alert('Child Added Succesfully');
clearCreateForm();
displayList();
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Child create error: ' + textStatus + " " + errorThrown);
}
});
}
I got it using this to put the errors in an object then append to the object and display in the div
error: function (jqXHR, textStatus, errorThrown) {
var errors = JSON.parse(jqXHR.responseText).ModelState
var errorText = Object.keys(errors).map((key) => errors[key])
console.log(Object.keys(errorText))
$('#formErrors').append(errorText.join(' <br>'))
}

JQuery AJAX post to asp.net webmethod never getting called?

I am trying to send data from my javascript to an aspx webmethod with ajax. the Success option of ajax post is fired but my web method never getting called.
the javascript code is:
$.ajax({
type: "POST",
url: '../About.aspx/GetWFData',
data: "{sendData: '" + 5 + "'}",
async: true,
success: function (result) {
alert("Bravo");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
});
and the webmethod in the code behind is:
[WebMethod]
public static string GetWFData(string sendData)
{
return String.Format("Hello");
}
Try to use below code to see if it works.
var params = '{sendData:' + values + '}';
$.ajax({
type: "POST",
url: '../About.aspx/GetWFData',
data: JSON.stringify(params),
async: true,
success: function (result) {
alert("Bravo");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
});
And refer to http://elegantcode.com/2009/02/21/javascript-arrays-via-jquery-ajax-to-an-aspnet-webmethod/ for more info. Try to disable request validation on a page.http://www.asp.net/whitepapers/request-validation

Just another jQuery AJAX not POST parameters correctly

I've googled many similar situations, but none of them could solve my problem. Please take a look at my code:
JavaScript:
$.ajax({
type: 'POST',
url: 'alarmInfo.aspx',
data: {request:'BasicGpaInfo'},
dataType: "json",
success: function (data) {
alert(data);
},
error: function () {
alert("Error in loading alarm information!");
}
});
ASP.NET:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["request"] == "BasicGpaInfo")
{
Response.Write(BasicGpaInfo());
}
else
{
Response.Write("Nothing");
}
}
This always returns "Nothing" and break point tells that Request.Form is null. And I have tried with GET and Request.QueryString which gives the same situation.
I guess there's something wrong with data in ajax function and I've tried with the following things that won't help:
data: $.param({request:'BasicGpaInfo'})
data: "{request:'BasicGpaInfo'}"
data: {request:'BasicGpaInfo'}
It won't work on all Web Browsers.
Please give some advice. Thanks!
I tested your code and it runs fine. However it always returns "Error in loading alarm information!" because you are not returning Json from the server.
Javascript is fine, once you return json, it will go into success.
You are returning the whole page, and your ajax method is getting the whole html instead of Json from BasicGpaInfo()
try putting a breakpoint in alert, and you will see all the data come inside data
error: function (data) {
alert("Error in loading alarm information!");
}
alternatively try
error: function (data) {
alert(data);
}
Here is the full code
$.ajax({
type: 'POST',
url: 'Default.aspx/BasicGpaInfoWebMethod',
data: { request: 'BasicGpaInfo' },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (data) {
alert("Error in loading alarm information!");
//alert(data); // uncomment to see the whole response
}
});
and your webmethod will be :
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string BasicGpaInfoWebMethod(string request)
{
return request;
}
Try this JSON.stringify before post. For using JSON.stringify in IE<=7 include json2.js file from json.org
$.ajax({
type: 'POST',
url: 'alarmInfo.aspx',
data: JSON.stringify({ request: 'BasicGpaInfo'}),
dataType: "json",
success: function (data) {
alert(data);
},
error: function () {
alert("Error in loading alarm information!");
}
});

aspx and jquery.ajax is always returning an error

This code worked fine in mvc2, but moving back to traditional ASPX (because of Sharepoint 2010). I am encountering errors. Can anyone tell me what I am doing wrong for this framework?
This ajax call is in the $.ready
$.ajax({
type: "POST",
dataType: "json",
data: 'siteName=a&siteUrl=b',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
code behind
[WebMethod]
public static string DoesNameUrlExist(string siteName, string siteUrl)
{
//do something
return someString;
}
I get an error everytime.
You need to send JSON to the service and indicate that you're doing so via the contentType header:
$.ajax({
type: "POST",
contentType: 'application/json',
data: '{"siteName":"a","siteUrl":"b"}',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
More info here: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Also, if you're using jQuery 1.4, you can drop the dataType. jQuery will infer JSON automatically based on the response's Content-Type header.
Ajax calls in jQuery will always give you an error if you declare your contentType as json and the response content type is anything but json. If the response from your WebMethod has something different (such as html or text), you'll always get that error. You can set that response type on your method like this:
[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string DoesNameUrlExist(string siteName, string siteUrl)
Outside of WebMethods this can also be achieved like this:
Response.ContentType = "application/json";

Resources