Solved

Converting to Angular, working with JSON from API call

Posted on 2014-10-08
10
473 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Replace 17 by 22 to 24
0
 

Author Comment

by:jcnelson84
Comment Utility
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
where did you put the page?
0
 

Author Comment

by:jcnelson84
Comment Utility
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
Comment Utility
Fast answers with example of the code and comments to help me understand. Great Expert.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

763 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

11 Experts available now in Live!

Get 1:1 Help Now