0

I am getting output in console like {}, Now I am checking it in if condition, it does not work

$.ajax({
  ...
  success: function(data){
   if (data.length) {
        if(data.length === 0){
            $('.library_info_tbl tbody').prepend('<tr><td class="text-center centeralign" colspan="8">No Data Available!</td></tr>');
        }
        else{   
        }
    }
  });

If data contains {}, it does not check if condition i.e if(data.length === 0) does not work in the code.

3
  • data appears to be a plain object, not an array? Commented Nov 5, 2017 at 6:50
  • Arrays [] have a length property, objects {} don't (unless you added one yourself.) Commented Nov 5, 2017 at 6:51
  • sucess : function(response) { console.log(response.data) } //can you tell the output Commented Nov 5, 2017 at 6:51

3 Answers 3

2
if (data.length) { ...... }

Above condition stops it from entering the inner block because 0 is treated as false, This the reason you are not able to execute your inner statement:

if(data.length === 0)
Sign up to request clarification or add additional context in comments.

Comments

0

Try following:

//if data is array 
if (data.length) {     
   $('.library_info_tbl tbody').prepend('<tr><td class="text-center centeralign" colspan="8">No Data Available!</td></tr>');
}
else 
{   
}

//if data is object

if(jQuery.isEmptyObject(data)){//do something }
else{ }

5 Comments

if i write console,log(data); the output appears like {}
the above code does not work if(!data){//do something } else{ }
if (!data) doesn't test for an empty object; even empty objects are truthy.
you are returning array or single object from your ajax method? @Nida
jQuery.isEmptyObject(data) this can be used to check empty object. I updated my answer. Try it @Nida
0

Object in Javascript does not have a length property in their prototype.

If you are trying to find the length then first determine if it is an array or not.

success(result){
    if(result instanceof Array && result.length){ ... }
}

instanceof will determine if result is of type Array. Thus ensuring you can safely use length.

Hope it helps :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.