Yogesh M Yogesh M - 1 year ago 53
AngularJS Question

Alert if JSON Data is Empty - Code not working

I want to check if json data is empty or not.

if json its empty, i want to alert

orders Not Found
If its not empty, i want to alert
orders found

if user not logged in, there won't be any token in his localstorage. so he will get a 500 error when browser requests the API URL. then I want to alert
along with the
failed status reason

my dev is sick, so tried my self. its not going too well.

Tried the below code, not at all working.

headers: {'Authorization': 'Token '+ localStorage.getItem("token")}})
.success(function(response) {


alert(" orders NOT found");


alert("orders found");

.error(function(response,status) {

return ;


Any help will be thankfull.

Answer Source

if you are trying to do in Angular js, then you can try the code below using callbacks:

      method: 'GET',
      url: 'http://localhost.com/activeorders/?format=json',
      headers: {
          'Authorization': 'Token '+ localStorage.getItem('token')
    }).then(function successCallback(response){ // this callback will be called asynchronously when the response is available
          if (response.data.length == 0){
              console.log("orders NOT found")
         // or if you just return an array json by php for example
          //if (response.length == 0) {
              //console.log("orders NOT found")
      }, function errorCallback(response){ // called asynchronously if an error occurs or server returns response with an error status.
          if (response){

If you are using an external file .json type, you can try :

menuApp.controller("dynamicMenuController", function($scope, $http) {
$http.get('config/menu.json').success(function(data) { 
    if(data.length == 0){
    else {alert('some here!')}

If your json is in another domain, an external domain . In this case , I suggest you look at JSONP instead, here's an example http://fdietz.github.io/recipes-with-angular-js//consuming-external-services/consuming-jsonp-apis.html:

 $http.jsonp('http://teckstack.com/api/get_recent_posts/?callback=JSON_CALLBACK').success(function (data) {
    console.log("success callback");
    if(data.length == 0){
    } // response data 
}).error(function (data) {
    console.log("failed callback");