jQuery + ASP.NET 4.0 ajax page method not working - asp.net

I have used whole lots of options resolving this, but it is not working.
My breakpoint is not hit in the Web Method. Also, the success function is being called, however, entire page content is returned not the string "hello".
My page does not at all use asp.net ajax scriptmanager. It uses plain jQuery only. I am using ASP.NET 4.0.
In brief, my page method is defined as:
[WebMethod]
public static string Populate()
{
return "hello";
}
The ajax call is:
$.ajax({
url:'WebForm3.aspx/Populate',
data:{},
dataType:"json",
type:"GET",
success: function(msg) {
alert("success");
},
error: function(msg, text) {
alert(text);
}
});

Page methods only work when POSTed to, like this:
$.ajax({
url:'WebForm3.aspx/Populate',
data: '{}',
dataType:"json",
type:"POST",
contentType: 'application/json; charset=utf-8',
success: function(msg) {
alert("success"); },
error: function(msg, text) {
alert(text);
}
});
Don't forget to quote the data argument: data: '{}'.

Related

call a static method in User Control from js or ajax

I am trying to call a static method in User Control from js or ajax.
It is possible to do this if the code method lies directly in WebForm but it is not possible to do it if we put the code method in UserControl and then put this UserControl in a WebForm.
Code Behind:
[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public static string GetNameFromCodeBehind (string name)
{
return "Hello from Code-Behind, " + name ;
}
AJAX Code:
$.ajax({
type: "POST",
url: "MyUserControl.ascx/GetNameFromCodeBehind",
data: JSON.stringify({ name: "Anton" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: true,
success: function (data) {
alert(data.d);
},
error: function (e) {
alert(e.statusText)
}
});
Ajax Error:
Not Found
If GetNameFromCodeBehind is inside MyUserControl.ascx, then it will be able to find a URL. Moreover, you have written the name of static method as callFromCodeBehind. So, you need to write the URL sccordingly

Call code-behind function from java script in c#

Is it even possible? To call a code-behind c# function from java script in a visual web part?
It is a complex function so converting all codes to client side is not an option.
I want the logic that is there in this function to happen without a page refresh.
Thanks.
We can call a method in codebehind from the JQuery AJAX call and depending upon the status whether it is error or success the corresponding method will be executed.
function MyMethod() {
$.ajax({
type: "POST",
url: "CodeBehind.aspx/ClearData",
contentType: "application/json;charset=utf-8",
data: '',
dataType: "json",
success: function (data, textStatus) {
closePopUpwindow1();
},
error: function (data, textStatus) {
closePopUpwindow2();
}
});}
[WebMethod]
public static void ClearData(){
Page.SetGridSessionData(gridID, null);
}
If the server side method is successfully executed then closePopUpwindow1 method is executed else closePopUpwindow2 method will be executed.
You can use j Query ajax to call server side method and get the response to be used in java script.
This article has simple and good example to show what you need to do.
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
Java script
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}

Jquery Ajax error for asp.net page

I have a very simple page and a [WebMethod] inside it which returns a simple message. I would like to show this message through $.ajax on client side. however my website is using rewrites rules so my url becomes readable to user.
EX:
Actual webpage: www.mysite.com/about // which has about folder and a user control inside it
there is no aspx page for this instead i am using a method which gets a webpage data which is actual html page and show the content on user control.
here is Jquery part.
$(document).ready(function () {
$('.info a').click(function () {
$.ajax({
type: 'POST',
url: '/about/showServer', //which url to put here
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("result.d");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
});
});
});
C#
[WebMethod] // this method is in the user control
public static string showServer()
{
return "Hello from server";
}
How to call this method from client using $.ajax
appreciate your time and help.
EDITS
I have this structure for my website
mysite.com/about
/about/defualt.aspx --> which loads the user controls
user controls resides in
mysite.com/ConLib/Custom/about.ascx/showServer
So i set it to like this
url: '/ConLib/Custom/about.ascx/showServer',
BUT i see error in chrome developer tool in XHR request "404 error" because when you type mysite.com/conlib/blah blah ..reqrites does not allows this and throws 404 error..
Your ajax success method should be this:
alert(result.d);
Instead of this:
success: function (result) {
alert("result.d");
}
and url should be:
url: "Default.ascx/showServer", // UserControlPage/MethodName
you need to decorate your web method
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
public static string showServer()
{
return "Hello from server";
}
If your WebMethod is inside a User Control, then it needs to be moved to the ASPX page. See this post:
How to call an ASP.NET WebMethod in a UserControl (.ascx)
The url: param should be in the form of '/MyPage.aspx/showServer'

$.ajax success not executing

I have in my .js file a function that call a webservices method called getStudents:
[WebMethod(Description = "white student list")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Job> getStudents(long classId)
{
return (new classManager()).getStudents(classId);
}
the method is callled like:
function loadStudents() {
var parameters = JSON.stringify({ 'classId': 0 });
alert(parameters);
$("#ProcessingDiv").show('fast', function() {
$.ajax({
type: "POST",
url: "myWebService.asmx/getStudents",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
$("#ProcessingDiv").hide();
var students= response.d;
alert('yes');
},
error: function(request, status, error) {
alert(request.responseText);
}
,
failure: function(msg) {
alert('somethin went wrong' + msg);
}
});
});
}
$(document).ready(function() {
loadStudents();
});
when i debug,the service web method is executed successfully but i don't get my alert('yes') and neither msg error.
What's wrong?
If you're returning (serialized to JSON) List of objects, then in response you will get JS array of JS objects, so (assuming Job has property p) try response[0].p for p value from first element.
note: I don't know ASP.NET, so maybe response is serialized in another way, thats where tools like Firebug (or other browsers Dev tools) are extremely useful - because you can look how exactly you'r http requests and responses looks like.
ps. And change alert to console.log and look for logs in Firebug console - its better than alert in many, many ways ;]

using jQuery AJAX with asp.net webservices always goes to error: instead of success:

Issue
I have an aspx page with jQuery code to send an ajax request over to an asmx web service file (on the same website). The response that comes back is not consistent, however, it consistently fires the "error" jQuery callback as opposed to the "success" call back. The status code inconsistently varies between 200, 12030, and 12031. The responseText of the message to the callback inconsistently varies between [blank] and the actual XML that the json webservice returns. I debugged the code, and the webservice does actually execute without any exceptions.
ASPX Code
//Code omitted for brevity
<script type="text/javascript">
jQuery(document).ready(function()
{
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CallDequeue.asmx/Dequeue",
data: "{}",
dataType: "json",
success: function(Msg)
{
alert('success:' + Msg.responseText);
},
error: function(Msg)
{
alert('failed:' + Msg.status + ':' + Msg.responseText);
}
});
});
</script>
//Code ommitted for brevity
Web Service Code
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class CallDequeue : System.Web.Services.WebService
{
[WebMethod]
public string Dequeue()
{
return "{\"d\":{\"FirstName\":\"Keivan\"}}";
}
}
When you mark the service as a ScriptService, it automatically handles the JSON serialization. You shouldn't manually serialize the response.
If you want the return to come back as "FirstName", then you can use a DTO class to control the syntax. Just returning a string, it would come back as {'d':'Keivan'} instead of {'d':{'FirstName':'Keivan'}}.
[ScriptService]
public class CallDequeue : System.Web.Services.WebService
{
public class PersonDTO
{
public string FirstName;
}
[WebMethod]
public PersonDTO Dequeue()
{
var p = new PersonDTO();
p.FirstName = "Keivan";
return p;
}
}
A few changes to the calling syntax:
jQuery(document).ready(function() {
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CallDequeue.asmx/Dequeue",
data: "{}",
dataType: "json",
success: function(Msg) {
// Unless you're using 2.0, the data comes back wrapped
// in a .d object.
//
// This would just be Msg.d if you return a string instead
// of the DTO.
alert('success:' + Msg.d.FirstName);
},
error: function(Msg) {
alert('failed:' + Msg.status + ':' + Msg.responseText);
}
});
});
You can read more about ASP.NET AJAX's .d wrapper here, if you're interested.
Update:
Using ASP.NET 2.0, you need to install the ASP.NET AJAX Extensions v1.0. Additionally, make sure your web.config is configured for ASP.NET AJAX (most specifically the HttpHandlers section).
This question will most likely help you.
Otherwise, I converted this web service to a page method and it worked immediately. Do you have that option?
CS:
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string Dequeue()
{
return "{\"d\":{\"FirstName\":\"Keivan\"}}";
}
}
ASPX:
<script type="text/javascript">
jQuery(document).ready(function()
{
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "test.aspx/Dequeue",
data: "{}",
dataType: "json",
success: function(Msg)
{
alert('success:' + Msg.responseText);
},
error: function(Msg)
{
alert('failed:' + Msg.status + ':' + Msg.responseText);
}
});
});
Check this and other Encosia articles out for more information.
you say it's json, but it returns xml. i see a slight disconnect there.
Such a simple answer. My web.config wasn't ajax enabled so all calls (regardless of my webservice being a scriptservice) were returning XML instead of pure json.
Try marking up your web method with [ScriptMethod]
As in:
[WebMethod]
[ScriptMethod]
My thanks to all the responders here.
Be sure to add these attributes in front of the methods to be used
[WebMethod]
[ScriptMethod]
Not sure when the ScriptMethod is needed ?
Curiously, he did NOT have the [Script Service] and the [WebMethod] in his download code.
Anyway, the aJax 500 12030 12031 errors are gone after the above changes.

Resources