Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

333
Visualizações
Returning Bool to AJAX request

This must be a really simple answer, but i cannot see where I am going wrong.

Just typing a test AJAX request with c# code behind. I cannot get the c# to return a true/false statement, or I cannot get the AJAX to recognise it as true/false.

  [WebMethod]
    public static bool testme(int testnumber)
    {
        if (testnumber < 12)
        {
            return true;             }
        else
        {

            return false;
                }

    }

AJAX:

<script>
        $(document).ready(function () {
            $('#test').click(function () {
               $.ajax({
                   type: "post",
                    url: "WebForm1/testme",
                    data: { testnumber: 13 },
                    contentType: "application/json; charset=utf-8",
                    datatype: "json",
                    success: function (data) {
                        if (data) {
                            console.log("true");
                        }
                        else {
                            console.log("false");
                        }
                    },
                    Error:function(error){
                        console.log("error");
                    }
                });
            });
        })


    </script>

Button:

<input type="button" id="test" value="click me"/>

The console.log is showing true, even though the number I am entering is greater than 12, which should return the "false" bool from the c# method.

console.log is returning a full page render see picture

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

your if(data) check is checking truthiness, data is going to be an object, so look at it's properties and you can find C#'s result.

If you're unfamiliar with JS truthiness, look it up for a better description: but each variable is considered to be truthy if it has a valid value, if it's null or undefined (or 0 or '') then it will not be considered truthy and will fail a boolean check.

about 4 years ago · Santiago Trujillo Relatório

0

When you get a response from a WebMethod like this you have to use a .d to reference the value. Your current code simply checks to see if you got a response, and most likely always evaluates to true.

<script>
        $(document).ready(function () {
            $('#test').click(function () {
               $.ajax({
                   type: "post",
                    url: "WebForm1/testme",
                    data: { testnumber: 13 },
                    contentType: "application/json; charset=utf-8",
                    datatype: "json",
                    success: function (data) {
                        if (data.d) {
                            console.log("true");
                        }
                        else {
                            console.log("false");
                        }
                    },
                    Error:function(error){
                        console.log("error");
                    }
                });
            });
        })
    </script>

One pointer as well that can help you figure out what is going on would be to use the network tab of you browsers developer tools (F-12) to see the response format that is coming back from the server. It isn't just returning true or false it is returning d: true or d: false thus the change I mentioned.

about 4 years ago · Santiago Trujillo Relatório

0

Whenever I have to use Ajax, I return from the function JSON object. For e.g:

return Json(new { result = true });

and in AJAX:

<script>
        $(document).ready(function () {
            $('#test').click(function () {
               $.ajax({
                   type: "post",
                    url: "WebForm1/testme",
                    data: { testnumber: 13 },
                    contentType: "application/json; charset=utf-8",
                    datatype: "json",
                    success: function (data) {
                        if (data.result === true) {
                            console.log("true");
                        }
                        else {
                            console.log("false");
                        }
                    },
                    Error:function(error){
                        console.log("error");
                    }
                });
            });
        })


  </script>
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda