0

I've been pulling my hair out trying to get the $http.json() to properly return a result set of objects. I have locally stored examples of the same response and they work fine.

Can anyone look at this code and tell me what I'm doing wrong? It has to do with returning $http or something in that bit.

Demo: http://plnkr.co/edit/x325wZ4mwi9DNM8tAxgH?p=preview

sitesbyjoe
  • 1,861
  • 15
  • 21
  • 1
    I can't run a successful test because your server is not allowing CORs. I'm getting: No 'Access-Control-Allow-Origin' header is present on the requested resource. for http://sitesbyjoe.com/angular-tests/typeahead/schools.php?callback=JSON_CALLBACK – nempnett Jul 01 '14 at 00:09
  • possible duplicate of [How to tie angular-ui's typeahead with a server via $http for server side optimization?](http://stackoverflow.com/questions/15930339/how-to-tie-angular-uis-typeahead-with-a-server-via-http-for-server-side-optimi) – Rob J Jul 01 '14 at 00:21

1 Answers1

1

You seem to have changed your plunker. The first one where you were using $http.jsonp call seems close but with CORs issues it is hard to test - you should definitely check the encoding type of your JSONP returned data is correct. However...

I would structure the $http.get as per the code below. Now that you have dropped $http.jsonp in favour of $http.get, also note that you may now need to explicitly unpack the returned JSON data string into a javascript object via jsonDecode. Lastly you will likely have to unwrap your server response to return just the json payload with no JSON_CALLBACK() wrapper.

  var url = 'http://sitesbyjoe.com/angular-tests/typeahead/schools.php?callback=JSON_CALLBACK'
  $http.get(url).success(function(data) {
      console.log(data);
      $scope.schools = angular.jsonDecode(data);
  });
nempnett
  • 225
  • 2
  • 7
  • Would you just put this code as-is inside the Controller? – sitesbyjoe Jul 01 '14 at 05:32
  • I created a new plunk with your suggestions but I'm still having the same issue. I also added a header to allow the cross domain requests. http://plnkr.co/edit/eVRzgOOUuynXSZBM77W1?p=preview – sitesbyjoe Jul 01 '14 at 05:42
  • OK - CORS Issue is resolved. But in your current plnkr the AJAX call for data never happens because schools is defined as a function not a property on $scope. You can either change schools to be a property (like in my code sample above) or in your html file you can change 'stuff in schools' to be 'stuff in schools()' (so it is a fn call). Bigger problem is that it still won't work until you get the correct media/encoding type set up on return data from server: use text/javascript for JSONP – nempnett Jul 03 '14 at 15:54
  • FYI: Making schools a function call means the AJAX call to server happens on every key press in the text box. You'll want fn approach if you plan to pass typed text to server at some point to make data call leaner. – nempnett Jul 03 '14 at 15:55