0

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. :)

2

2 Answers 2

1

data: "{}", should be just data: {}, or just remove it if not in use,,..

Sign up to request clarification or add additional context in comments.

Comments

0

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 + '"}'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.