1

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.

3
  • 1
    Debug your empty responce. If it comes like responce.data where data should be array, than check array length. If data is object - check for any own property presented Commented Jun 11, 2016 at 9:00
  • Check with If(response.length ===0) Commented Jun 11, 2016 at 9:40
  • can you put your response log here. maybe you handling it wrong. Commented Jun 11, 2016 at 9:40

3 Answers 3

2

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");
});
Sign up to request clarification or add additional context in comments.

2 Comments

It is necessary to make sure that your webservice method is returning a json with the correct header .
thank you. but seems not to be working :( . check - pastebin.com/2uvePTsn
2

If you want to check if a JS object or JSON is empty ({}), for example, your object is response:
Object.keys(response).length === 0 && response.constructor === Object

Comments

0

Try

if( Object.keys(JSON.parse(response)).length == 0 ){
  alert("err")
}

2 Comments

its response.data.lenght
go for the official documentation.. check the script.js in the last example here docs.angularjs.org/api/ng/service/$http

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.