Solved

Converting to Angular, working with JSON from API call

Posted on 2014-10-08
10
481 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
10 Comments
 
LVL 110

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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Adding Clickable Links to JQuery Data Items 24 54
Windows 10, 64 bit WAMP - won't start 9 29
Format Date 7 28
Difference between Highcharts and Mapbox 10 44
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

734 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