Why is my Ajax not working?

I tried calling the method from Ajax code, and my ajax code just doesn't get into Method. what could be the problem in my code?

C # Method:

[WebMethod]
public static bool UserNameExists(string sendData)
{
    bool a;

    a = DataCheck.CheckDBUser(sendData);

    return a;
}

Ajax:

$('#Button2').click(function () {
    var name = document.getElementById('<%= UserTxt.ClientID %>').value;
    $.ajax({
        type: 'POST',
        url: 'Register.aspx/UserNameExists',
        data: '{ }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(msg) {
            if (msg.d == true) {
                $("#UserLb").text("User Name is OK!");
            } else {
                $("#UserLb").text("User Name NOT avliable!");
            }
        }
    });
});

Please note: when I used alert (); the team just check to see if it works - that was fine.

Thank.

+4
source share
2 answers

Your method expects a parameter that you do not pass when calling ajax. Do the following:

$('#Button2').click(function () {
    var name = document.getElementById('<%= UserTxt.ClientID %>').value;

    $.ajax({
        type: 'POST',
        url: 'Register.aspx/UserNameExists',
        data: {sendData:name },
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(msg) {
            if (msg.d == true) {

                $("#UserLb").text("User Name is OK!");
            } else {
                $("#UserLb").text("User Name NOT avliable!");
            }

        }
    });
});

and also remove single quotes from data:'{}', it should bedata: {}

+4
source

You need to define some data to send the function. You can also determine that a method should accept HttpPost as follows:

[WebMethod]
[HttpPost]
public static bool UserNameExists(string sendData)
{
    bool a;

    a = DataCheck.CheckDBUser(sendData);

    return a;
}

:

$('#Button2').click(function () {

    var name = document.getElementById('<%= UserTxt.ClientID %>').value;


    $.ajax({
        type: 'POST',
        url: 'Register.aspx/UserNameExists',
        data: {sendData: "Hello" },
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(msg) {
            if (msg.d == true) {

                $("#UserLb").text("User Name is OK!");
            } else {
                $("#UserLb").text("User Name NOT avliable!");
            }

        }
    });
});
+1

Source: https://habr.com/ru/post/1535161/


All Articles