简体   繁体   中英

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?

Object.keys should work:

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

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

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....
                }
            })

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM