PK10
PK10

Reputation: 362

How to get no data found message if json in empty

I am doing some json parsing using jquery. I want to raise a message if no data in json array. So I used the code bellow and got the condition true but no message appended in html div.

my code:

$( "#refresh" ).click(function() {
    $.getJSON("http://ec2-72-44-51-113.compute-1.amazonaws.com:8001/get_latest_verification", function(obj){
        if(json.length==0){
             $('<p>no updates found</p>').appendTo('#rr');
        }
    });
});

Can Anyone correct me.

Upvotes: 0

Views: 1327

Answers (4)

Rui
Rui

Reputation: 4886

You can try

$.isEmptyObject(obj) 

instead of json.length == 0

This will work for both empty arrays and empty objects

See the documentation page here.

Upvotes: 0

Alex
Alex

Reputation: 11245

What is you question? Just check what request finished and json is empty or request is failed (use promise pattern):

var url = "http://ec2-72-44-51-113.compute-1.amazonaws.com:8001/get_latest_verification";
$( "#refresh" ).click(function() {
     $.getJSON(url).done(function (json) {
          if(!json || json.length === 0){
              $('<p>no updates found</p>').appendTo('#rr');
           }
     }).fail(function () {
         $('<p>no updates found</p>').appendTo('#rr');
     });
});

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67187

You can try this too,

if($.isEmptyObject(obj)) { //do you work here }

Documentation : isEmptyObject

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148514

You have a small error :

You should check if(obj.length==0)

And not as you did.

why ?

becuase this is the argument of your callback which is declared as :

function(obj){...}

notice :

I surely hope that you have cors enable on the server because running your code display:

*XMLHttpRequest cannot load http://ec2-72-44-51-113.compute-1.amazonaws.com:8001/get_latest_verification. Origin http://run.jsbin.com is not allowed by Access-Control-Allow-Origin.*

And I dont see any allow -domain header in the reponse :

Accept:application/json, text/javascript, */*; q=0.01
Cache-Control:no-cache
Origin:http://run.jsbin.com
Pragma:no-cache
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36

Upvotes: 3

Related Questions