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 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){..}
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);
}
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 '='
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.