Javascript – cant access JSON response in callback AngularJS

angularjsjavascript

In my net tab I am seeing the responses coming back but I can't get access to the data for some reason.

Here is the direct link: https://github.com/users/gigablox/contributions_calendar_data

Using Angular 1.2 rc2. Tried a couple different ways…

$http

var url = "https://github.com/users/gigablox/contributions_calendar_data?callback=JSON_CALLBACK";
$http.jsonp(url).success(function(data){
    console.log(data);
});  

$resource

var handle = $resource('https://github.com/users/gigablox/contributions_calendar_data',{},{
  get:{
    method:'JSONP',
    isArray: false, //response is wrapped as an array. tried true and false
    params:{callback:'JSON_CALLBACK'}
  }
});

handle.get().$promise.then(
function(data){
    console.log(data);
}).
function(error){
    console.log(error); //undefined but 200 OK on response?
});

Best Answer

The problem here is that you are requesting a flat file, so the server isn't wrapping the data in the javascript function call specified by the jsonp_callback querystring parameter. Further CORS is preventing you from fetching the file directly using $http/xhr.

In general, if you use $http.jsonp the specified callback function needs to reside in the global scope, and then you need to 're-angularify' the response data.

Here's an example using the wordpress api: http://jsfiddle.net/Rjfre/23/

HTML

<div ng-controller="MyCtrl" id='ctl'>
  <h2 ng-show="data">Data from callback</h2>
  <pre>{{data}}</pre>

  <h2 ng-show="success">Success</h2>
  <pre>{{success}}</pre>

  <h2 ng-hide="data">Error</h2>
  <pre>{{error}}</pre>
</div>

SCRIPT

var myApp = angular.module('myApp', []);

function MyCtrl($scope, $http) {
    $scope.name = 'Superhero';
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=jsonp_callback";

$http.jsonp(url).then(
        function(s) { $scope.success = JSON.stringify(s); }, 
        function(e) { $scope.error = JSON.stringify(e); } );
}

function jsonp_callback(data) {
    var el = document.getElementById('ctl');
    var scope = angular.element(el).scope();
    scope.$apply(function() {
        scope.data = JSON.stringify(data);
    });
}