Reputation: 1
I am trying to execute a method in ASP.NET from Jquery
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MyMessages.aspx?id=66&epslanguage=sv/test",
data: "{}",
dataType: "json",
error: function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
},
success: function() {
alert("it works" );
}
})
code behind:
[WebMethod]
protected void test()
{
test.Text = "works";
}
I get errormessage redayState: 4 and status 200 when I do this. I don't understand the problem. I am vey new at this. :)
Upvotes: 0
Views: 2237
Reputation: 947
as a first your method should be static and public so instead of this
[WebMethod]
protected void test()
{
test.Text = "works";
}
it should be
[WebMethod]
public static void test()
{
test.Text = "works";
}
this is the first fix the second you can't access the test.text so if u wanna make sure it works you can write it in this way
$.ajax({
type: "POST",
contentType: "application/json",
url: "MyMessages.aspx/test",
data: "{}",
dataType: "json",
error: function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
},
success: function() {
alert("it works" );
// and here use jQuery to set the control test
$("#<%=test.ClientID%>".text("Works");
}
})
so your final code should be like this
[WebMethod]
public static void test()
{
//test.Text = "works";
}
and Ajax method
$.ajax({
type: "POST",
contentType: "application/json",
url: "MyMessages.aspx/test",
data: "{}",
dataType: "json",
error: function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
},
success: function() {
alert("it works" );
// and here use jQuery to set the control test
$("#<%=test.ClientID%>".text("Works");
}
})
I did change the URL for u and if you wanna pass parameters you pass them on Data Section of Ajax method some thing like this
'{"fname":"' + fname + '","lname":"' + lname + '","email":"' + email + '","address":"' +
I wish it helps you address + '"}'
Upvotes: 0
Reputation: 65254
data: "{}",
should be just data: {},
or just remove it if not in use,,..
Upvotes: 1