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

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

Related

In Asp.net, 'Post' Ajax Request Will 'Get'

In my Asp.net Project and in Controller with name 'AjaxController' I have this Action Method:
[HttpPost]
public ActionResult GetList(int year)
{
var res="";
// some codes
return Json(res);
}
And in Js file :
$.ajax({
url: '/Ajax/GetList/',
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: 2000,
async: false,
success: function (response) {
// some codes
},
error: function (xhr, status, error) {
alert(error);
},
});
I expect that this method ONLY called with 'POST' but when I check My logs I will see some errors like:
AbsoluteUri :https://example.com/Ajax/GetList/
* Message :A public action method 'GetList' was not found on controller 'Controllers.AjaxController'.
That shows Called as 'GET', NOT 'POST'.
What and where is problem?
Thancks In Advanced
Couple of suggestions from my end -
Remove contentType and async attributes unless really required
Pass JSON object to 'data'
Also, use debugger and breakpoints generously to figure out yourself where your code is going astray
$.ajax({
url: '/Ajax/GetList/',
type: "POST",
//contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {year: 2000},
//async: false,
success: function (response) {
debugger;
// some codes
},
error: function (xhr, status, error) {
debugger;
alert(error);
},
});

Web Method not called in ajax aspx web form

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.

Replace error list instead of append Json

HI i have the bleow json code to validate a form when data is enetred wrong, if the data is enetered wrong more than once when create button is clicked it appends all the data again and still has the first set of errors, is there a way to remove the current errors and replace them with updated ones when the button is clicked?
function CreateChild() {
$("#formErrors").remove();
$.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) {
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>'))
}
});
}
To achieve that, simply use .html() instead of .append()
$('#formErrors').html(errorText.join(' <br>'));
See http://api.jquery.com/html/ for details of this method.

Unable to find dynamically created control when JSON is used

I am calling JSON method on selected index changed of the drop down list which is as follows
function StepImplementationScript(SelectedValue,UniqueField) {
debugger;
$.ajax({
type: "POST",
url: "DynamicForm.aspx/StepImplementationScript",
data: "{strSelectedValue: " + SelectedValue + ", strUniqueField: '" + UniqueField + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(response) {
alert("OnSuccess" + response.d);
if (msg) {
msg.close();
}
},
error: function(jqXHR, exception) {
alert(jqXHR.responseText);
},
failure: function(response) {
//alert("Onfailure" + response.d);
}
});
}
In this 'StepImplementationScript' method of server side when i try to find dynamically created control, the controls are not getting find and coming as null.
Selected change event i have written in Jquery through which i have called the JSON method.
This is the same page (DynamicForm.aspx) on which controls are created dynamically.
Why this is so ? and how should i resolve this issue ???

getting data as the page loads

I'm trying to get data back after an element is ready in the DOM. I'm trying to use the load function from JQUERY but I get a message .load() is not a function.
Is there a best practice when using ajax to get data for an element (in my case a div) during a page load? I'm using ASP.NET and calling a webmethod in code behind.
Here is my ajax/jquery code:
$(document).ready(function () {
$(function () {
$("[id$=divArea]").load()(function () {
$.ajax({
type: "POST",
url: "apage.aspx/Role",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
alert("got data from Role");
},
error: function (data) {
alert("failed to get data from Role");
}
});
});
});
Thanks.
$(document).ready() is for calling code once the DOM is ready - therefore, if I have understood you correctly, you don't need to include $("[id$=divArea]").load()(function () {
It should work like this:
$(document).ready(function () {
$(function () {
$.ajax({
type: "POST",
url: "apage.aspx/Role",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
alert("got data from Role");
},
error: function (data) {
alert("failed to get data from Role");
}
});
});
});
By the way - it was probably a paste error, but you also omitted the $(document).ready closing }); in the code you posted.
I think that the problem it's the code itself, try the code like this
$(document).ready(function (){
$("[id$=divArea]").load('apage.aspx/Role',function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
})
});

Resources