The succes of Ajax is not working

1

Currently I have a jax call that takes me to my C # method to be able to authenticate my user, but this Ajax call is not working the succes part, since if it sends me to the method I want but in the end he does not send me the alert he should send when going through succes:

Ajax code

function autenticarme() {
    var nick = $(".txtNick").val(); 
    var pass = $(".txtPass").val();
    $.ajax({
        url: "login.aspx/conectarBD",
        data: "{ nick: '" + nick + "',password: '" + pass + "' }",
        type: "POST",
        dataType: "JSON",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            alert("Entro");
        }, error: function (xhr, status, error) {
            alert("Error");
        }
    });
}

C # method code

#region conectarBD
[WebMethod]
public static string conectarBD(string nick,string password)
{
    Conexion conn = new Conexion();
    string respuesta = conn.Autentificar(nick,password);
    return respuesta;


}
#endregion
    
asked by David 25.03.2017 в 00:26
source

2 answers

1

The problem is in the dataType parameter: "json" that you are using in the AJAX query.

This parameter tells jQuery the format that will come from the server. That is to say, in this case you are indicating to him that a JSON will come, which is not happening. You are only sending plain text, that's why the error function will be executed. If you delete this parameter, jQuery will assume that only plain text will come.

So I see that there are two options:

1) Or delete this parameter and return a string in C #, as it is done now.

2) Or, you change the C # method to return a JSON. Changing the return by:

return {data: respuesta};
    
answered by 25.03.2017 в 05:03
0

Regardless that the flow of the request has been completed, the Ajax Request expects a success: true to be able to know if everything went correctly, otherwise it would always be reaching error .

In the Code Behind you will have to serialize the response to send the result as successful:

[WebMethod]
public static object conectarBD(string nick, string password)
{
    try{
        Conexion conn = new Conexion();
        string respuesta = conn.Autentificar(nick,password);

        return new { success = true, data = respuesta };
    }
    catch (Exception e) {
        return new { success = false, data = e.Message };
    }
}
    
answered by 25.03.2017 в 01:06