I am trying to read data from this API, but it is not working, I have an input box where I enter the isbn number and then get the data, using jsonp. Could you possibly help me in identifying where my error("Cannot read property 'title' of undefined") is?
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(isbn){
var infoUrl = isbn.info_url;
var thumbnailUrl = isbn.thumbnail_url;
var title = isbn.details.title;
var publishers = isbn.details.publishers;
var isbn13 = isbn.details.isbn_13;
console.log(isbn.info_url);
}
});
}
Open Library's API expects bibkeys to be prefixed with their type and a colon, rather than just the number alone:
function add(){
var isbn = 'ISBN:' + $("#isbn").val();
// ...
The colon also means the value should be URL-encoded, which jQuery can do for you:
$.ajax({
url: "https://openlibrary.org/api/books?jscmd=details&callback=?",
data: { bidkeys: isbn },
dataType: "jsonp",
Then, the data it returns reuses the bibkeys you provided as properties:
{ "ISBN:0123456789": { "info_url": ..., "details": { ... }, ... } }
To access the book's information, you'll have to first access this property:
success: function(data){
var bookInfo = data[isbn];
console.log(bookInfo.details.title);
// etc.
}
Example: https://jsfiddle.net/3p6s7051/
You can also retrieve the bibkey from the object itself using Object.keys():
success: function (data) {
var bibkey = Object.keys(data)[0];
var bookInfo = data[bibkey];
console.log(bookInfo.details.title);
// ...
}
Note: You can use this to validate, since the request can be technically successful and not include any book information (i.e. no matches found):
success: function (data) {
var bibkeys = Object.keys(data);
if (bibkeys.length === 0)
return showError('No books were found with the ISBN provided.');
// ...
Example: https://jsfiddle.net/q0aqys87/
I asked a professor, and this is how she told me to solve it:
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(data){
var thumb=data["ISBN:"+isbn+""].thumbnail_url;
....
}
});
}
Related
What ever I do, I keep getting the same error. The only thing I have found that might of helped is the JSON.parse, but I still get the same problem. console log gives data as [{"ID":"2","Name":"EAA2"}]
I split it into two functions as I didn't want to keep going back to the api everytime a user selects/de-selects an option.
I have also tried the following:
Changing vars to lets
Passing data.d from the update to the populate
function populateAvailableAuthorities() {
var list = $('#availableAA');
var data = JSON.parse($('#AAJSON').val());
var auths = $('#tbSelectedAA').val();
list.empty();
$.each(data, function (key, entry) {
if (!~auths.indexOf(entry.ID + ';')) {
list.append($('<option></option>').attr('value', entry.ID).text(entry.Name));
}
});
}
function updateListboxes() {
var teams = '';
let aa = $('#AAJSON');
aa.empty();
$('#cblTeams input:checked').each(function () {
teams += $(this).attr('value') + ',';
});
if (teams.length > 1) {
teams = teams.substr(0, teams.length - 1);
$.ajax({
type: "POST",
url: '<%# ResolveUrl("~/api/Authorities.asmx/FetchByTeam") %>',
data: '{teams: "' + teams + '"}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
aa.val(JSON.stringify(data.d));
populateAvailableAuthorities();
}
});
}
}
It would seem that "over-stringifying" is an issue with JSON. If I doubled the JSON.parse or removed the JSON.stringify it all works correctly.
Annoying!!
I'm running into issues with _.map (using underscore.jshttp://underscorejs.org).
getCalories: function() {
var encode = "1%20";
var calSource = "https://api.edamam.com/api/nutrition-data?app_id=#&app_key=#";
_.map(ingArray, function(elem)
{
return $.ajax(calSource, {
dataType: "json",
jsonp: "jsonp",
data: "ingr=" + encode + elem,
complete: function(r) {
var obj = JSON.parse(r.responseText);
var calorie = obj.calories;
calArray.push(calorie);
console.log(calArray);
}
});
});
},
I need to use the latest iteration of calArray in another function. However, it always comes up as undefined. So I inserted a console.log above and this is what I get:
app.js:177 is the console.log
Is this a scoping issue? Also, if it's logging prior to the push then I can see why it's coming up as undefined. How do I get around it?
I believe underscore's map produces a new array, in your case the new array will contain a bunch promises (ajax-requests)
You may want to assign this to a variable first, something like below:
getCalories: function () {
var encode = "1%20";
var calSource = "https://api.edamam.com/api/nutrition-data?app_id=#&app_key=#";
var requests = _.map(ingArray, function(elem) {
return $.ajax(calSource, {
dataType: "json",
jsonp: "jsonp",
data: "ingr=" + encode + elem
});
});
$.when.apply($, requests).then(function(results) {
console.log(results); // can you take a screenshot of this output
var calories = _.map(results, function(result) {
return JSON.parse(result.responseText).calories;
});
calArray = calArray.concat(calories);
});
}
I would like to two add property Id and ButtonId to the exisiting json result. I have pasted the below js code for reference and I would like to pass the jsonresult to MVC controller. As of now it returns null. please help to proceed. Thanks.
my final result should look like this
json{"Groups":{"Id":"2","ButtonId":"1142","1186","1189"},
{"Id":"3","ButtonId":"1171","1173","1174","1175","1176","1187"},
{"Id":"4","ButtonId":"1177","1178","1179"}} etc..
var btnlist = {Groups: {Id:"", ButtonId: ""}};
$.each($(".buttonData"), function (index, value) {
var values = value.id.split(':');
grpid = values[0].split('-')[1];
btnid = values[1].split('-')[1];
console.log('grpid=' + grpid + ' btnid=' + btnid);
if (typeof (btnlist['Groups'][grpid]) == 'undefined') {
btnlist['Groups'][grpid] = [];
}
btnlist['Groups'][grpid].push(btnid);
});
$.ajax({
type: "POST",
url: "#Url.Action("Home", "Menu")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(btnlist) ,
success: function (result) {
console.log('json' + JSON.stringify(btnlist));
console.debug(result);
},
error: function (request, error) {
console.debug(error);
}
});
This is the json result before pushing into the multidimensional array
The json result, where the properties Id and ButtonId is inserted behind.
null result passed to the controller
With assistance of my colleague, the desired output is as below. This is for other programmers who face similar issue with JSON array. Thanks.
var btnlist = [];
btngrps = $('.btn-sort-container');
$.each(btngrps, function(k, v) {
btnarr = {};
gid = $(this).attr('id');
grpid = gid.split('-')[1];
btnarr.Id = gid.split('-')[1];
btnobjs = $(v).find('.buttonData');
if (btnobjs.length) {
btnarr['btnId'] = [];
$.each(btnobjs, function(bk, bv) {
btnid = $(bv).attr('id').split('-')[2];
btnarr['btnId'].push($(bv).attr('id').split('-')[2]);
});
console.debug(btnarr);
btnlist.push(btnarr);
}
});
console.debug(btnlist);
Output on console
: http://i.stack.imgur.com/oJ3Dy.png
I am using a JQuery autocomplete to display a list of available courses. I am doing a post to get a list of Courses from the server, I manipulate the data to be in the expected format, and I pass it to the autocomplete function. The problem is that it does not work unless I hard copy and paste the values newSource and paste them into source.
The variable newSource = ["Enc1001","ENC1002","Enc1003","ENC1101"....etc].
The ajax post to get the data from the server
//Auto complete for search box
$('#AdditionalSearch').on('input', function () {
var source = [];
var inputValue = $('#AdditionalSearch').val();
if (inputValue !== '') { //the value is not empty, we'll do a post to get the data.
url = "/Course/CourseSearch";
$.ajax({
method: 'POST',
dataType: 'json',
contentType: 'application/json',
cache: false,
data: JSON.stringify({ "searchCourseValue": inputValue }),
url: url,
success: function (data) {
if (data.Ok) {
var myData = JSON.parse(data.data);
var newSource = '[';
$.each(myData.ResultValue, function (index, item) {
if ((myData.ResultValue.length -1) == index)
newSource += '"' + item.Name+'"';
else
newSource += '"'+ item.Name + '",';
});
newSource += "]";
console.log(newSource);
source = newSource;
}
setNameAutoComplete(source);
},
error: function (jqXHR) {
console.log(error);
}
});
} else { //The user either delete all the input or there is nothing in the search box.
//The value is empty, so clear the listbox.
setNameAutoComplete(source);
}
});
//Passing the source to the auto complete function
var setNameAutoComplete = function (data) {
console.log(data);
$('#AdditionalSearch').autocomplete({
source: data
});
}
Is there something that I am missing here?
When you literally paste newSource = ["Enc1001","ENC1002","Enc1003","ENC1101"....etc]in your code, you are building an array object. However, in your success method, you are building a string (the string-representation of that same object). What you want to be doing is build an actual array in stead.
...
success: function (data) {
if (data.Ok) {
var myData = JSON.parse(data.data);
var newSource = [];
$.each(myData.ResultValue, function (index, item) {
newSource.push(item.Name);
});
console.log(newSource);
source = newSource;
}
setNameAutoComplete(source);
},
...
I am making a web application using Jersey and JQuery for client-side.
I have the following URL that returns a JSON string:
http://localhost:8080/messenger/webapi/messages/1
returns:
{"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"}
when typed into the browser.
Now I am attempting to get this data client-side using the following JQuery functions:
var rootURL = "http://localhost:8080/messenger/webapi/messages";
$(function() {
$('#btnRegister').click(function() {
var username = $('#username').val();
addMessage();
});
function addMessage() {
var url = rootURL;
$.ajax({
type: 'GET',
url: rootURL +"/1",
dataType: "json", // data type of response
success: (function(data) {
var obj = jQuery.parseJSON(data);
alert('ID: ' + obj.id);
})
});
}
});
EDIT: When the "btnRegister" is pressed nothing is displayed at all
which just doesn't make sense to me.
There is some unwanted $ wrapping in success callback function, also there is no need to parse the response as you set dataType:'json'. For better understanding of $.ajax() read documentation here.
$(function() {
$('#btnRegister').click(function() {
var username = $('#username').val();
addMessage();
});
function addMessage() {
var url = rootURL;
$.ajax({
type: 'GET',
url: rootURL + "/1",
dataType: "json", // data type of response
success: function(data) {
//----^----------- remove the $ sign
alert('ID: ' + data);
}
});
}
});
You can access the value using obj.prop or obj['prop']
var obj= {"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"};
alert(obj.author);
alert(obj['author']);