ShaiEitan
ShaiEitan

Reputation: 171

Why my Ajax not working?

i tried to call to a method from Ajax code, and my ajax code simply not get into the Method. what can 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!");
            }
        }
    });
});

Notice: when i used alert(); command just to check if its running - it was ok.

Thank you.

Upvotes: 4

Views: 83

Answers (2)

Kristian Barrett
Kristian Barrett

Reputation: 3762

You need to define some data to send to the function. Also you can define the method should take a HttpPost like this:

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

    a = DataCheck.CheckDBUser(sendData);

    return a;
}

And define some data to send to the method:

$('#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!");
            }

        }
    });
});

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

Your method is expecting a parameter which you are not passing in ajax call. Do like this:

$('#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 be data: {}

Upvotes: 4

Related Questions