Link to home
Start Free TrialLog in
Avatar of jcnelson84
jcnelson84

asked on

Converting to Angular, working with JSON from API call

I am interested in using Anjular.js though not sure how to work with the JSON from my current API call. Here is the code I have right now that works at www.jtsbooks.com/more/test.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>JSON Sample</title>
</head>
<body>
    <div id="placeholder"></div>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" ></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.getJSON("/more/book.php?isbn=0133020266",function(result){      
      $.each(result, function(i, field){
        $("div").append(field + " ");
      });
      
      console.log(result); 
var bookinfo = result.response.page 
 
document.getElementById("demo").innerHTML =
bookinfo.pages + "<br>" +
bookinfo.isbn10 + "<br>" +
bookinfo.isbn13 + "<br>" +
bookinfo.title + "<br>" +
bookinfo.author + "<br>" +
bookinfo.binding + "<br>" +
bookinfo.publisher + "<br>" +
bookinfo.edition;
    });
  });
});
</script>
</head>
<body>

<button>Get JSON data</button>
<h2>JSON Object Creation in JavaScript</h2>

<p id="demo"></p>


<div></div>

</body>
</html>

Open in new window


So my question is how can I convert this to work with Angular.JS? I have found several examples online that work but the JSON used in those objects have '[]' to separate out objects and the json I am getting from my API call has only '{}'. That is the only thing I have noticed that is different. I have PHP running on the backend to actually make the call and then it passes the JSON returned back.

Thanks,
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

As a rule with JSON, the square brackets encapsulate arrays and the curly brackets encapsulate objects.
http://json.org

What is in the PHP script that creates the JSON string?
Avatar of leakim971
Check this page : http://jsfiddle.net/w7469apx/

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

var myCtrl = myApp.controller("myCtrl", ["$scope", "myBookService", function($scope, myBookService) {
    $scope.bookinfo = [];
    myBookService.getBook("0133020266").then(function(pageData) {
        $scope.bookinfo = pageData;
    });
}]);

myApp.service("myBookService", ["$http", "$q", function($http, $q) {
    return {
        getBook: function(isbn) {
            var deferred = $q.defer();
            var url = "/more/book.php?isbn=" + isbn;

            /* REAL WORLD :
            $http.get(url).success(function(data, status) {
                deferred.resolve(data);
            }).error(function(data, status) {
                deferred.reject(data);
            });
            */

            // FOR THE SAKE OF THIS DEMO, WE SIMULATE THE AJAX CALL WITH A 2seconds timer :
            setTimeout(function() {
                var data = {"response":{"@attributes":{"status":"ok","version":"12"},"label":{"@attributes":{"plid":"3258","name":"JTSbooks"}},"page":{"@attributes":{"name":"bookinfo"},"count":1,"pages":"624","current_page":1,"isbn10":"0133020266","isbn13":"9780133020267","title":"Managerial Economics (7th Edition)","author":"Paul Keat - Philip K Young - Steve Erfle","binding":"Hardcover","msrp":245.2,"publisher":"Prentice Hall","published_date":"2013-01-13","edition":"7","rank":46652,"rating":0,"_amazon_item":null,"image":"http:\/\/ecx.images-amazon.com\/images\/I\/513ffF3L4yL._SL75_.jpg"}}};
                var page = data.response.page;
                deferred.resolve(page);
            }, 2000);
            return deferred.promise;
        }
    }
}]);
 

Open in new window

Avatar of jcnelson84
jcnelson84

ASKER

Ray Paseur. The JSON string I get from the API has no [ ] in it. I am using the PHP to call this http://api2.campusbooks.com/12/rest/bookinfo?key=jTsg3MPAivcRlLsNvC7N&isbn=0133020266&format=json
which is the same result I get from the PHP call http://www.jtsbooks.com/more/book.php?isbn=0133020266

 leakim971, Thanks for the example. It clears a lot of my confusion up. If I take out the simulated AJAX call then it should look something like this?  

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

var myCtrl = myApp.controller("myCtrl", ["$scope", "myBookService", function($scope, myBookService) {
    $scope.bookinfo = [];
    myBookService.getBook("0133020266").then(function(pageData) {
        $scope.bookinfo = pageData;
    });
}]);

myApp.service("myBookService", ["$http", "$q", function($http, $q) {
    return {
        getBook: function(isbn) {
            var deferred = $q.defer();
            var url = "http://www.jtsbooks.com/more/book.php?isbn=" + isbn;
            
            $http.get(url).success(function(data, status) {
                deferred.resolve(data);
            }).error(function(data, status) {
                deferred.reject(data);
            });
                        
            var page = data.response.page;
            deferred.resolve(page);           
            return deferred.promise;
        }
    }
}]);
 

Open in new window


I tried to run it this way but it did not work though the JSON that you had copied into the Var data looks the same as I get if I go to http://www.jtsbooks.com/more/book.php?isbn=0133020266 or the direct link have above so I am not sure where the issue is here to get this to work with the actual API call.
Replace 17 by 22 to 24
I switched out those lines but it still does not seem to work. Is this what you meant?

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

var myCtrl = myApp.controller("myCtrl", ["$scope", "myBookService", function($scope, myBookService) {
    $scope.bookinfo = [];
    myBookService.getBook("0133020266").then(function(pageData) {
        $scope.bookinfo = pageData;
    });
}]);

myApp.service("myBookService", ["$http", "$q", function($http, $q) {
    return {
        getBook: function(isbn) {
            var deferred = $q.defer();
            var url = "http://www.jtsbooks.com/more/book.php?isbn=" + isbn;
            
            $http.get(url).success(function(data, status) {                
                var page = data.response.page;
                deferred.resolve(page);               
                return deferred.promise;
            }).error(function(data, status) {
                deferred.reject(data);
            });
                                 
        }
    }
}]);

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Still not working for me. Ha, I don't know what the missing link is here. I can get it to work if I have the JSON file in the code but I can not get these calls to work for some reason.
where did you put the page?
Actually it is working, I was testing it in jsfiddle and it did not work there but there must be something about external calls that don't work through that. I put it on my server and it works great. Thank you very much, now that I have data that comes through that I can play with it is going to help me alot to learn and understand how to use Angular. here is the link to it on my server you can see it works. Thanks again http://www.jtsbooks.com/more/books/test.html
Fast answers with example of the code and comments to help me understand. Great Expert.