Weird string comparision when perforing ajax request in javascript - javascript

Have a weird problem in javascript. I am performing a check against the backend with Jquery to check if the mail is already existing in the database. The answer is either true or false.
The problem is that if the answer is true i get that the data variable contains "true", but the check:
data == "true"
fails anyway. The code seem somehow to evaluate "true" == "true" to false.
success: function(data) {
if (data == "true") {
emailAlreadyIsUsed = true;
} else {
emailAlreadyIsUsed = false;
}
}
Does anybody know what this depend on?
I am new to develop in javascript, is there a good way to debug this? I have steped through this code in chrome checking the values of the variables.

It's because it's not a String, try data == true or if(data){... should work. How is it being set server side?

If you want to compare string with other string you can do this in following way:
success: function(data) {
emailAlreadyIsUsed = (data.indexOf('true') === 0);
}
But it is really strange that your code not working.
You can try strict comparison ===.
success: function(data) {
if (data === "true") {
emailAlreadyIsUsed = true;
} else {
emailAlreadyIsUsed = false;
}
}
Or try to compare two strings:
success: function(data) {
if (String(data) === "true") {
emailAlreadyIsUsed = true;
} else {
emailAlreadyIsUsed = false;
}
}

Thanks all for your answers.
What I in the end made to make this work is to change the dataType to "json". Then the variable data contains a boolean variable which I can normaly use.

Related

ajax post refresh page on a bad request

I have an ajax post that looks like this:
$.ajax({
type: "post",
dataType: "html",
url: "/MyController/MyAction",
data: AddAntiForgeryToken({
SomeValue: "Abc"
}, "#FormIdFromWhereToCopyAntiForgeryTokenFrom"),
success: function (response) {
if (response === "True") {
//do something
} else {
//call the function to try again in 10 seconds.
}
},
error: function (e) {
//call the function to try again in 10 seconds.
}
});
Now in certain scenarios, it is possible that this function will return an error, these are very rare scenarios, but possible and I want to handle them. For the purpose of the question, I don't think it important to dive into them. In any case, on my server side I have setup a check when an error happens with that scenario. I capture it and then I return a response that would normally tell browser to refresh itself. But since this is an ajax call, it won't do it. Here is the code for that:
public class CustomExceptionHandler : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
var exception = filterContext.Exception;
if (exception != null)
{
var exceptionType = exception.GetType();
var someType= typeof(SomeExceptionType);
if (exceptionType.IsInstanceOfType(someType) || someType == exceptionType)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.RawUrl);
return;
}
}
}
}
As you can see above, the idea is to tell the page to refresh itself and the problems will be resolved after that. However, I'm not sure how to check in my javascript in the error section, that the server sent back a Redirect Result so I can tell the browser to refresh.
Would I be looking at the headers or something else? Could you post an example of how I can solve this?
You can simply set a timeout to refresh the page, like this:
else {
//call the function to try again in 10 seconds.
settimeout(function(){
location.reload();
}, 10000);
}
Or have I missunderstood the question?

Apply conditions in Ajax success Method on received data from Django's view

I'm working on a Django project in which I need to handle a form via ajax.I'm sending ajax request to Django view and getting back the response in JSON format, now I need to apply if-else conditions on that data but these conditions are not working, always run the first condition in any case.
Here's my code:
Django's view:
auth = getauth()
service = discovery.build('cloudbilling', 'v1', http=auth, cache_discovery=False)
name = 'projects/' + projectName
billing_request = service.projects().getBillingInfo(name=name,)
billing_response = billing_request.execute()
data = billing_response
print(json.dumps(data))
if 'billingAccountName' in data:
b_response = data
b_response['msg'] = True
return HttpResponse(json.dumps(b_response), content_type='application/json')
else:
b = {}
b['msg'] = False
return HttpResponse(json.dumps(b), content_type='application/json')
Here's my ajax code:
$(document).on('submit', '#projectForm', function (e) {
var message;
e.preventDefault();
$.ajax({
url: '{% url 'users:selectProject' %}',
type: 'POST',
data:{
project_id:$('#project').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
},
dataType: 'json',
success:function (data) {
message = data.msg;
console.log(message);
if(data.msg = 'false'){
console.log('Message is False');
$('#message').addClass('show');
}else if(data.msg = 'true') {
console.log('Message is True');
$('#message2').addClass('show');
$('#enableApi').prop('disabled', false);
$('#project_btn').prop('disabled', true);
}
}
});
})
It always display 'Message is False' even if console.log('message') display true.
what am I doing wrong?
Help me, please!
Thanks in Advance!
The == shouldn't be used here because inspection reports usages of JavaScript equality operators which may cause unexpected type coercions.It is considered a good practice to use the type-safe equality operators === instead of its regular counterpart ==
So, it can be solved by using === instead of ==
if(data.msg === false){
console.log('Message is False');
$('#message').addClass('show');
}else if(data.msg === true) {
console.log('Message is True');
$('#message2').addClass('show');
$('#enableApi').prop('disabled', false);
$('#project_btn').prop('disabled', true);
}
The issue seems to be with the conditional statement
if(data.msg = 'false'){..} & else if(data.msg = 'true'){..}
This two statements are assigning the value, instead of checking for the condition
Replace single equal(=) with double(==) or triple equals(===). Also note the difference between (==) and (===). There will be no type conversion in ===.
if(data.msg === false){..} & else if(data.msg === true){..}
This:
if(data.msg = 'false'){
Should be:
if(data.msg == 'false'){
If you want to compare use '==', but if you want to set a value use '='

jquery can't alert ajax response

I'm trying to alert the Ajax response from the code below but somehow nothing gets alerted.
function get_fee(){
if ( $('#type').val() == 'hardcopy' ) {
setTimeout(function(){
var title = $('#title').val();
$.ajax({
type: 'POST',
url: 'convert.php',
data: {hardcopy: '1', title: title},
success: function(response) {
if (response == 'false') {
alert(response);
}
}
});
}, 1000);
}
}
However, if the above code was written without
if (response == 'false') {
}
and the alert( response ) is called, it works flawlessly. I would have adopted the later approach but unfortunately the value of var response can either be true or false.
Use:
if (response) {
alert(response);
} else { alert("Some Error Message"); }
Try taking off the quotes from around the 'false'
if (response == false) {
}
or just
if (!response) {
}
You don't need the double (" ") quotes for a boolean value.
if (response == false) {
alert(response);
}
You can use:
error: function(response){
alert(response);
}
If you are sending the strings "true" or "false", try removing extra whitespace that could be there from php file:
if (response.trim() == 'false') {
alert(response);
}
You can have following options
Use any one from them :
1) As for boolean comparison dont use speech marks so use false instead of 'false'
if (response == false) {
}
2) directly use response for decision making
if (!response) {
}
3) if (response == false)
alert("whatever you wish to put")
4) if (!response)
alert("whatever you wish to put")
Finally figured out the problem.
The response returns a string as value rather than a boolean. So I changed its data type to boolean before it is received by ajax (from 'false' with quotes to false without quotes), and i was able to evaluate it as a boolean with
if (response == false) {
alert(response);
}
Thanks to everyone who contributed.

Javascript AJAX Call Scope - Probably silly

I'm having a problem with something that is likely a simple error.
As you will notice below, I have a check for duplicate function that references external PHP checking a database. The PHP is working, and returning data.
When I use duplicationCheck.done() and parse the data, my if statement responds correctly (i.e., if the user has entered a duplicate, this checks that. HERE'S the issue: Despite my if statement below functioning correctly, when isDuplicate is set to true, it appears as undefined when the console.log command is called below the done() function. I can't figure out why. With my research, I think that it is a problem with the async nature of the AJAX call?
Thank you for your time. Any ideas?
$("#username_submit").click(function() {
function checkForDuplication(username) {
return $.ajax({
url: 'static/experiments/computerized_handwriting/random_assignment.php',
type: 'POST',
data: {userName: username}
});
}
var duplicationCheck = checkForDuplication($('input:text').val());
var isDuplicate;
duplicationCheck.done(function(data){
var response = JSON.parse(data);
if(response.data['json_array'] == "duplicate"){
isDuplicate = true;
alert("dup");
} else {
isDuplicate = false;
}
});
console.log(isDuplicate);
....
This is due to the asynchronous nature of ajax.
You need to check for the duplication once it returns from the server in the done function.
But your duplicationCheck variable is not a reference to the function, but what it is returning.
The proper way would be like this:
$("#username_submit").click(function() {
$.ajax({
url: 'static/experiments/computerized_handwriting/random_assignment.php',
type: 'POST',
data: { userName: $('input:text').val()}
}).done(function() {
var response = JSON.parse(data);
if (response.data['json_array'] == "duplicate") {
isDuplicate = true;
alert("dup");
}
else {
isDuplicate = false;
}
console.log(isDuplicate);
});//done
});//submit click
....

jquery ajax boolean validation

I am doing this for a username validation, search for a name in DB through ajax, in if condition irrespective of the return value (true of false), I am getting an error message. That means it's taking only false. When I am debugging, ajax is working fine and it's taking the values of true or false according to situation and I am calling it as a normal jQuery validation with rules and messages. please help me out.
jQuery.validator.addMethod("shortNameCheck",function(value,element){
if (value != null && value != "") {
shortName = $('#shortName').val();
$.ajax({
dataType: 'json',
url: clientsetup.props.shortNameValidation,
data: "shortName=" + shortName + "&hierarchyNodeId=" + hirNodeId,
type: 'POST',
success: function (data) {
if (data.shortNameCheck === 'true') {
return false
} else {
return true;
}
}
});
} else {
return true;
}
});
use this --
<script type="text/javascript">
var bool = true;
console.log(typeof bool); // return boolean
if(bool === true)
{
alert('correct');
}
</script>
change --
if (data.shortNameCheck === 'true')
To --
if (data.shortNameCheck === true)

Categories

Resources