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