Solved

Converting to Angular, working with JSON from API call

Posted on 2014-10-08
10
477 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 109

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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
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
 
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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
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…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.

776 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