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

Viewed 71

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?

2 Answers

Object.keys should work:

enter image description here

enter image description here

enter image description here

I suggest you double-check the params sent to the success function.

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

Related