0

In Angular sidemenu project

.controller('PlaylistsCtrl', function($scope, $http) {
    $scope.basePath = 'http://localhost/iongallery/rest/';
    
    $http({
        method: 'POST',
        url : $scope.basePath+'ajax_get_data_client.php',
        data : {'operation': 'showMonths'}
    }).then(function success(data){
        $scope.months = data;
        console.log($scope.months[1].years);
    }, function error(data){
        
    });

When i Load the app 2 request got generated, one without any data {} and one with data {'operation': 'showMonths'} .

enter image description here

The request without any data dosen;t fetch andy response and the request with data fetch [{"month":"2","years":"2016"},{"month":"3","years":"2016"},{"month":"4","years":"2016"},{"month":"5","years":"2016"}]

this json.

But, while unable to read the JSON. Give Eror TypeError: Cannot read property 'years' of undefined

1 Answer 1

2

$http.then() has another signature

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

The response object has these properties: data – {string|Object} – The response body transformed with the transform functions. status – {number} – HTTP status code of the response. headers – {function([headerName])} – Header getter function. config – {Object} – The configuration object that was used to generate the request. statusText – {string} – HTTP status text of the response. so you need change lines

}).then(function success(data){
            $scope.months = data;
            console.log($scope.months[1].years);
        }, function error(data){

into

}).then(function success(response){
        $scope.months = response.data;
        console.log($scope.months[1].years);
    }, function error(data){
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I was missing extra data parameter while reading JSON ` response.data`.

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.