Yogesh M Yogesh M - 5 months ago 25
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
failed
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.

<script>
$http.get("http://localhost.com/activeorders/?format=json",{
headers: {'Authorization': 'Token '+ localStorage.getItem("token")}})
.success(function(response) {

if(response=="[]")
{

alert(" orders NOT found");


}
else
{

alert("orders found");
}

.error(function(response,status) {

alert("failed");
alert(status);
}
return ;
});

</script>


Any help will be thankfull.

Answer

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

 $http({
      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){
             alert("failed");
          }
      });

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) { 
    console.log("success!");
    if(data.length == 0){
        alert('empty');
    }
    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){
       alert('empty');
    } // response data 
}).error(function (data) {
    console.log("failed callback");
});