jquery can't alert ajax response - javascript

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.

Related

Compare Javascript Ajax Response with String

I'm trying to compare the result from from ajax call with a string. My result is returning the correct result but i can't get the if statement to compare this with my string, any ideas?
$.ajax({
type: "POST",
url: "sessionCheck.php",
data: {id:mwdata},
success: function(html) {
if (html == "open"){
alert ("yes it's open");
}else if(html == "closed"){
alert ("no it's closed");
}
}
});
So the answer was to trim the result var result = $.trim(html);

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 '='

Weird string comparision when perforing ajax request in 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.

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)

Retrieve data from ajax query

So I've got a website where I want to click a button, check to see if the user has certain permissions, and if so popup a window to a new web page. On the java script I've got something like this:
function sendAjax(methodName, dataArray, success, error, category) {
var error2 = error || function () { };
$.ajax({
type: 'POST',
url: '/PermissionChecker' + methodName,
data: JSON.stringify(dataArray),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (r, s, x) { if (!success || success(r, s, x) != false) if (typeof (window.ChangeLogAdd) == 'function') { ChangeLogAdd(category); } },
error: error2
});
}
function CheckPermissions() {
sendAjax("CheckPermission", null, function (data) { var permission = eval('(' + data + ')'); if (permission == true) { alert('yay'); } else { alert('nay'); } }, null, 'Check Permission');
}
And the C# side is a simple function that does an if check and returns a bool. The function call goes through fine, but when it returns the bool I get a javascript error "Expected ']'". I assume this has something to do with my success function:
function (data) {
var permission = eval('(' + data + ')');
if (permission == true) {
alert('yay');
}
else {
alert('nay');
}
}
seeing as I didn't get this error before I tried what I'm doing there, so I was wondering how I would go about getting the data back from the ajax call to make pass the permission == true if/else check
Don't use eval for this purpose. It's unsafe and the source of many bugs. Just make the server respond with JSON and use $.getJSON.

Categories

Resources