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.
Related
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.
I am sending a post data to get a json string back:
My JSON string:
{"error":false,"success":"Added Website","website_id":"12"}
My Ajax request:
$('.publsher_add_website').on("submit", function() {
show_loader();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(data) {
if (data.success == false) {
ajax_error(data.error);
hide_loader();
} else {
console.debug(data);
console.log(data.error);
console.log(data.success);
console.log(data.website_id);
location.href = site_url + "publisher/websites?added=" + data.website_id + "#modal-verify";
hide_loader();
}
},
error: function() {
hide_loader();
}
});
return false;
});
Now, when I go to use the returned data all of them are undefined.I have used:
console.debug(data);
Which returns the json string above, but if I try to access them individually:
data.error;
data.success;
data.website_id;
They all return as undefined Why is this? How can I fix it?
You haven't provided a dataType in your $.ajax, so AJAX treats the response as a string, not an object. So, inside the success function, do this first:
success: function(data) {
data = JSON.parse(data);
Try parsing your json string to a json object to get your values:
data = JSON.parse(data);
I have an href in an html page and i have an AJAX request in a method in a javascript file.
When clicking on href i want to call the JS function and I am treating the response to add it to the second html page which will appear
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
var request = $.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {client_language: client_language, PIN_code:pin,client_phone:number}
});
request.done(function(msg) {
//alert(JSON.stringify(msg));
});
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
request.error(function(jqXHR, textStatus)
{
//MESSAGE
});
}
I tried with , and also to write the function with $('#idOfHref').click(function(){}); not working.
All I can see is the alert TEST and then nothing happens. I checked several posts here but nothing works for me.
Function can be corrected as,
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {"client_language": client_language, "PIN_code":pin,"client_phone":number},
success : function(msg) {
//alert(JSON.stringify(msg));
if (msg.ws_resultat.result_ok == true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
alert('Error Occured'); //MESSAGE
}
}
});
1. No need to assign ajax call to a variable,
2. Your further work should be in Success part of AJAX request, as shown above.
It's a bad practice use an onclick() so the proper way to do this is:
Fiddle
$(document).ready(function(){
$('#mylink').on('click', function(){
alert('onclick is working.');
miniReport(); //Your function
});
});
function miniReport(){
var client_account_number = localStorage.getItem('numb');
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {
'client_language': client_language,
'PIN_code': pin,
'client_phone': number
},
success: function(msg){
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
//Manage your error.
}
});
}
Also you have some mistakes in your ajax request. So I hope it's helps.
Rectified version of your code with document .ready
$(document).ready(function(){
$("#hrefid").click(function(){ // your anchor tag id if not assign any id
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data:{"client_language":client_language,"PIN_code":pin,"client_phone":number},
success : function(msg) {
if (msg.ws_resultat.result_ok == true)
{
window.open("account_details.html");
}
else
{
alert('some thing went wrong, plz try again');
}
}
}
});
});
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');
}
});
I have a javascript function that calls a generic function to make an ajax call to the server. I need to retrieve a result (true/false) from the callback function of the ajax call, but the result I get is always 'undefined'.
A super-simplified version of the generic function without all my logic would be:
function CallServer(urlController) {
$.ajax({
type: "POST",
url: urlController,
async: false,
data: $("form").serialize(),
success:
function(result) {
if (someLogic)
return true;
else
return false;
},
error:
function(errorThrown) {
return false;
}
});
}
And the function calling it would be something like:
function Next() {
var result = CallServer("/Signum/TrySave");
if (result == true) {
document.forms[0].submit();
}
}
The "result" variable is always 'undefined', and debugging it I can see that the "return true" line of the callback function is being executed.
Any ideas of why this is happening? How could I bubble the return value from the callback function to the CallServer function?
Thanks
Just in case you want to go the asynchronous way (which is a better solution because it will not freeze your browser while doing the request), here is the code:
function CallServer(urlController, callback) {
$.ajax({
type: "POST",
url: urlController,
async: true,
data: $("form").serialize(),
success:
function(result) {
var ret = ( someLogic );
callback(ret);
},
error:
function(errorThrown) {
return false;
}
});
}
function Next() {
CallServer("/Signum/TrySave", function(result) {
if (result == true) {
document.forms[0].submit();
}
});
}
I usually put any code to be executed on success inside the callback function itself. I don't think CallServer() actually receives the return values from the callbacks themselves.
Try something like:
function CallServer(urlController) {
$.ajax({
type: "POST",
url: urlController,
async: false,
data: $("form").serialize(),
success:
function(result) {
if (someLogic)
document.forms[0].submit();
else
// do something else
},
error:
function(errorThrown) {
// handle error
}
});
}
Edit: I'm not too familiar with jQuery, so I might be completely wrong (I'm basing this on the behavior of other frameworks, like YUI, and AJAX calls made without any framework). If so, just downvote this answer and leave a comment, and I will delete this answer.
Just found how to do it :) Declaring a variable and updating it accordingly from the callback function. Afterwards I can return that variable. I place the code for future readers:
function CallServer(urlController) {
var returnValue = false;
$.ajax({
type: "POST",
url: urlController,
async: false,
data: $("form").serialize(),
success:
function(result) {
if (someLogic){
returnValue = true;
return;
}
},
error:
function(errorThrown) {
alert("Error occured: " + errorThrown);
}
});
return returnValue;
}