Returning Bool to AJAX request - javascript

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>

So it turns out it was relativly simple, but not sure why it needs to be done. I got help from https://forums.asp.net/t/2023743.aspx?Ajax+Webmethod+not+firing+
I needed to change
//settings.AutoRedirectMode = RedirectMode.Permanent;
to
settings.AutoRedirectMode = RedirectMode.Off;
to my RouteConfig.cs and then everything worked fine.
If anyone knows why this isn't automatically changed when you add the System.Web.Services; or what this means i would love to know, anyway, all working great now.

Related

How to set false to ASP Button if Ajax result is success?

I am calling Ajax when user click the button. When calling ajax it will check the data with textbox whether the textbox value is already exist or not. If exist, then it should not return false, if the record is not found in database, jquery button should return true let it to save on database through server side.
Note:
My Ajax code is working. But when I the is exist and set return false this statement is not execute.
Here is my code:
$('#btnSaveFile').click(function () {
var fileNames = $('#txtFileName').val();
var flags = 'test';
alert('test='+flags);
$.ajax({
url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
method: 'post',
async:false,
contentType: 'application/json',
data: '{fileName:"' + fileNames + '",reportName:"TotalSales"}',
dataType: 'json',
success: function (data) {
if (data.d === 'dataExist') {
// it execute this loop, but after it execute it's going to server
$('#lblSaveErrorMsg').text('This filename already exist. Please change the name');
return false;
}
else {
return true;
}
},
error: function (error) {
alert('Please Call Administrator');
}
});
});
I found result myself.
Ajax is an Asynchronous. We cannot do return false when the result is success.
So I declare one variable outside of ajax and with the certain condition in success I set return false in outside of ajax code
This is my Jquery code
$('#btnSaveFile').click(function () {
var fileNames = $('#txtFileName').val();
var flag = 'returnTrue';
$.ajax({
url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
method: 'post',
async: false,
contentType: 'application/json',
data: '{fileName:"' + fileNames + '",reportName:"TotalSales"}',
dataType: 'json',
success: function (data) {
if (data.d === 'dataExist') {
flag = 'returnFalse';
$('#lblSaveErrorMsg').text('This filename already exist. Please change the name');
}
else {
alert('else');
return true;
}
},
error: function (error) {
alert('Please Call Administrator');
}
});
if (flag === 'returnFalse') {
return false;
}
});

Wrong result string compare jquery

I'm getting wrong string compare result in my ajax function:
$("#scan").click(function() {
id = 1;
$.ajax({
type: "POST",
data: { reqValue: id },
url: "http://localhost:8080/test-notifier-web/RestLayer",
success: function(data){
$.trim(data)
alert(data);
if ('OK' === data) {
alert("yes");
} else {
alert("no");
}
}
});
});
Data is returned from my Java servlet response, in fact i get an alert displaying "OK", then it shows me "no". What am I doing wrong?
You're calling $.trim() but not assigning the result to anything. Try trimming whitespace from the returned string before you compare, like this:
$("#scan").click(function() {
id = 1;
$.ajax({
type: "POST",
data: { reqValue: id },
url: "http://localhost:8080/test-notifier-web/RestLayer",
success: function(data) {
if ('OK' === data.trim()) {
alert("yes");
} else {
alert("no");
}
}
});
});
It's for this reason that returning a string from an AJAX request isn't a good idea. Look in to returning JSON instead.

Web service receiving null with jQuery post JSON

The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}

ajax Json return type not comming in success

I have following ajax call:
$.ajax({
type: "GET",
url: "/Company/validateForm",
dataType: "json",
data: {
'txtCompanyName': txtCompanyName,
'txtCompanyContactPerson': txtCompanyContactPerson,
'txtCompanyPhone': txtCompanyPhone,
'txtCompanyFax': txtCompanyFax,
'txtCompanyEmail': txtCompanyEmail,
'txtCompanyWebsite': txtCompanyWebsite,
'txtZipcode': txtZipcode,
'txtCountry': txtCountry,
'txtAddress1': txtAddress1,
'txtAddress2': txtAddress2,
'txtCompanyRegNo': txtCompanyRegNo
},
success: function (responceMessage) {
alert(responceMessage);
if (responceMessage != "1") {
alert(responceMessage);
} else {
saveCompanyInformation();
}
},
error: function () {
alert('failure');
}
});
I have made sure that call is going to server side and returning proper message in string format.
But when call from validateForm method on server side is returned, it directly goes to failure instead of success method.
I can't figure out what I'm doing wrong here.
Console is showing:
GET http://localhost:49273/Company/validateForm?txtCompanyName=+x&txtCompanyCon…ebsite=&txtZipcode=&txtCountry=&txtAddress1=&txtAddress2=&txtCompanyRegNo= 500 (Internal Server Error)
I just made cache:false in ajax and code worked.
It was as follows:
$.ajax({
type: "POST",
url: "/Company/validateForm",
cache:false,
dataType: "json",
data:
{
'txtCompanyName': txtCompanyName,
'txtCompanyContactPerson': txtCompanyContactPerson,
'txtCompanyPhone': txtCompanyPhone,
'txtCompanyFax': txtCompanyFax,
'txtCompanyEmail': txtCompanyEmail,
'txtCompanyWebsite': txtCompanyWebsite,
'txtZipcode': txtZipcode,
'txtCountry': txtCountry,
'txtAddress1': txtAddress1,
'txtAddress2': txtAddress2,
'txtCompanyRegNo': txtCompanyRegNo
}
,
success: function (responceMessage) {
if (responceMessage != "0") {
alert(responceMessage);
}
else {
saveCompanyInformation();
}
},
error: function () {
alert('failure');
}
});

How to return value in ajax call?

I want after keyup in input if data was 0 return is false if was not false return is true. but in my try always return is true in case data === 0:
$('input').live('keyup change', function () {
var result = true;
$.ajax({
type: 'POST',
dataType: 'json',
url: 'search_customer',
data: dataObj,
cache: false,
success: function (data) {
if (data == 0) {
alert('data is 0')
result = false;
} else {
alert('data is not 0')
}
}
})
//alert(result) this output always is 'true'
return result;
})
The .ajax() call returns at an arbitrary time in the future. The keyup and change handlers return (essentially) immediately.
Do the work in your success handler. Alternatively, you could set a global (or namespaced global) to the returned value, with the understanding that it would be invalid until the Ajax call completes.
You also need to make sure the data being returned is what you expect it to be, if the if statement itself isn't doing what you expect. That's a different issue than the return value from the event handler.
I see that you've selected async: false as your answer, but there is a better way - using a callback function.
$('input').live('keyup change', function () {
DoSomething(function(result) {
// this isn't blocking
});
})
function DoSomething(callback) {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'search_customer',
data: dataObj,
cache: false,
success: function (data) {
var result = data !== 0;
if (typeof callback === 'function') {
callback(result);
}
}
});
}

Categories

Resources