jquery ajax boolean validation - javascript

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)

Related

How to check if data returned from ajax as json is empty object or not

I have set this script for checking if the email address exists in the DB or not:
function checkemail(){
var e = document.getElementById("email").value;
if(e != ""){
document.getElementById("emailstatus").innerHTML = 'checking ...';
$.ajax({
type:'get',
url:'{!! URL::to('checkEmailExists') !!}',
data:{'email':e},
success:function(data){
// console.log(data);
if(Object.keys(data).length === 0)
{
document.getElementById("emailstatus").style.color = "red";
document.getElementById("emailstatus").innerHTML = e + " is NOT OK";
}else{
document.getElementById("emailstatus").style.color = "green";
document.getElementById("emailstatus").innerHTML = e + " is OK";
}
},
error:function(){
}
});
}
}
So the code works fine but the only problem is comes from this condition checking which always returns TRUE:
if(Object.keys(data).length === 0)
Basically, if I enter an email address that does not exist in the DB, this will be returned as data (results of console.log(data)):
{}
Otherwise, it will return this obj:
{
"id": 1,
"name": "Myname",
"email": "myemail#yahoo.com",
"email_verified_at": null,
"created_at": "2022-02-09T05:49:27.000000Z",
"updated_at": "2022-02-09T05:49:27.000000Z"
}
So I need to properly check if the returned object is empty or not.
But it looks like that if(Object.keys(data).length === 0) is not correctly checking that condition since it always TRUE & therefore the [email] is OK statement appears on page.
So how to properly check if the returned object is empty or not?
You can check for a specific property, if it's not there then it will be undefined, meaning you didn't get a success response.
Combine undefined with || to get a "value if not set", gives:
success:function(data) {
var success = (data.id || 0) > 0;
You could just check for if (data.id == undefined) but there are a number of caveats when comparing with undefined
Object.keys should work:
I suggest you double-check the params sent to the success function.
See below solution that have worked for me:
$.ajax({
url: url,
type: 'POST',
data: { par1: value1,
par2: value2 },
dataType: 'JSON',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
success: function(response)
{
if(Object.keys(response).length > 0)
{
//there is valid returned response
}
else
{
//no response keys returned
}
},
error: function (x, h, r) {
//deal with errors....
}
})

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.

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.

Javascript global variable not being set from ajax call [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Return Value from inside of $.ajax() function
I'm working on a CakePHP app that makes use of widespread AJAX calls to controllers. I'm stuck with one particular AJAX call in which I'm trying to assign the response from the controller to a JS global variable. Here is the code:
window.errors = "";
function setErrors(err) {
window.errors = err;
}
function ajaxCall(u, t, d, dt) {
var type = typeof t !== 'undefined' ? t : "post";
var dataType = typeof dt !== 'undefined' ? dt : "json";
var success = false;
var err = "";
$.ajax({url: url, data: "data=" + d, type: type, dataType: dataType,
success: function(d){
if(d.hasOwnProperty('success') === false) { //json response
for(var i in d) { //fetch validation errors from object
for(var j in i) {
if(typeof d[i][j] === "undefined") {
continue;
}
err += d[i][j] + "<br/>";
}
}
console.log(err); //<=== displays correct value
setErrors(err); //<=== but somehow this seems to be failing??
}
else {
if(d.success === "1") {
success = true;
}
}
}
});
return success; //<=== I suspect this might be the culprit
}
And this is how ajaxCall() is used:
function register() {
var data = {};
var $inputs = $("#regForm :input");
$inputs.each(function(){
data[this.name] = $(this).val();
});
data = {"User" : data }; //CakePHP compatible object
data = JSON.stringify(data);
//Here's the AJAX call
if(ajaxCall('https://localhost/users/add', 'post', data, 'json')) {
alert("Registered!");
}
else {
alert(window.errors); // <=== empty string
console.log("window.errors is: " + window.errors); // <=== empty string
}
}
But on the Chrome JS console, window.errors returns the correct value (non-empty, validation error string).
I found a similar question that possibly might be addressing my issue (the return success immediately following the $.ajax() is being executed before the success: callback). How can I fix this without drastically changing the code (also, I don't want to make this a synchronous call)?
Yes, you are right that the return statement runs before the success callback. You can't return the result from the function, as the function has to return before the success event can be handled.
Add a callback to the ajaxCall function, and call that instead of setting the success variable:
function ajaxCall(u, t, d, dt, callback) {
var type = typeof t !== 'undefined' ? t : "post";
var dataType = typeof dt !== 'undefined' ? dt : "json";
$.ajax({url: url, data: "data=" + d, type: type, dataType: dataType,
success: function(d){
if(d.hasOwnProperty('success') === false) { //json response
for(var i in d) { //fetch validation errors from object
for(var j in i) {
if(typeof d[i][j] === "undefined") {
continue;
}
err += d[i][j] + "<br/>";
}
}
callback(false, err);
} else {
callback(d.success === "1", "");
}
}
});
}
Send the code for handling the result into the ajaxCall function:
ajaxCall('https://localhost/users/add', 'post', data, 'json', function(success, err){
if (success) {
alert("Registered!");
} else {
alert(err);
}
});

Categories

Resources