Solved

Converting to Angular, working with JSON from API call

Posted on 2014-10-08
10
476 Views
Last Modified: 2014-10-08
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,
0
Comment
Question by:jcnelson84
  • 5
  • 4
10 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40368567
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?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 40368691
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

0
 

Author Comment

by:jcnelson84
ID: 40368923
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.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 40368977
Replace 17 by 22 to 24
0
 

Author Comment

by:jcnelson84
ID: 40369221
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

0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 40369263
sorry I was in my car. here the code :
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);               
            }).error(function(data, status) {
                deferred.reject(data);
            });
            return deferred.promise;                                
        }
    }
}]);

Open in new window

0
 

Author Comment

by:jcnelson84
ID: 40369430
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.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 40369442
where did you put the page?
0
 

Author Comment

by:jcnelson84
ID: 40369509
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
0
 

Author Closing Comment

by:jcnelson84
ID: 40369510
Fast answers with example of the code and comments to help me understand. Great Expert.
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now