0

Quick question:

I'm using jquery ajax to call a page that returns some json data. Sometimes it returns full of data and sometimes it returns empty as [].

I want the script to do different things if it comes back empty[] or with data. Everything is working fine when it returns with data, but I can't seem to get things to work when it returns empty as []. Here's what i have:

success: function (returndata){
      if (returndata === null)
      {
          $("#versionBox").remove();
      }
 else {
        $.each(returndata, function()
               {
                   var tag = this["name"];
                   var linkname = "textdisplay.php?flag=<?php echo $fs; ?>&ed=" + tag;
                       $('#versionBox').append("<p><a href='" + linkname + "'>" +  tag + "</a></p>");
               });

      }

But null doesn't seem to be the correct way to describe [] because the first part of this script isn't working.

Thanks for your advice.

Jeff
  • 3,943
  • 8
  • 45
  • 68

3 Answers3

3

What you perceive as "empty" is an array with no elements. Arrays have a length property, so:

if (returndata.length == 0) // "empty" return

This assumes that returndata is an array in every case (otherwise, it might have no length and you will get errors), but in your case it looks it is indeed.

Jon
  • 428,835
  • 81
  • 738
  • 806
2

First, check if it's an array Check if object is array?, then if its returndata.length == 0. Done & done!

if( Object.prototype.toString.call( returnData ) === '[object Array]' ) {
    if(returnData.length == 0)
        alert( 'it is []' );
}

The "is it an array" check isn't very satisfying, I know...

Community
  • 1
  • 1
david van brink
  • 3,604
  • 1
  • 22
  • 17
0
if (returndata){
    //if the return data has content
} else {
    //when it does not
}
gscragg
  • 145
  • 1
  • 7