Created
November 12, 2018 11:45
-
-
Save laymonage/0973decee8116c6212ec157ca5ffcfae to your computer and use it in GitHub Desktop.
Script to query Google books API and populate a table with the result.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function writeTable(items) { | |
/** | |
* Write items to table. | |
*/ | |
var tbody = $('tbody'); | |
tbody.empty(); | |
$(function() { | |
$.each(items, function(i, item) { | |
var author = item.volumeInfo.authors ? item.volumeInfo.authors[0] : '-'; | |
var thumbnail = item.volumeInfo.imageLinks ? item.volumeInfo.imageLinks.smallThumbnail : ''; | |
var img = thumbnail ? '<img src="' + item.volumeInfo.imageLinks.smallThumbnail + '">' : '-'; | |
var $tr = $('<tr>').append( | |
$('<td>').text(i + 1), | |
$('<td>').text(item.volumeInfo.title), | |
$('<td>').text(author), | |
$('<td>').html(img), | |
).appendTo('tbody'); | |
}); | |
}); | |
$('#book-results').removeAttr('style'); | |
} | |
$(document).ready(function() { | |
$('form').submit(function(event) { | |
// get form data | |
var formData = { | |
'kata_kunci' : $('input[name=kata_kunci]').val(), | |
}; | |
// process the form | |
$.ajax({ | |
type : 'GET', | |
url : 'https://www.googleapis.com/books/v1/volumes?maxResults=40&q=' + formData.kata_kunci, | |
dataType : 'json', // expected return type | |
}) | |
// using the done promise callback | |
.done(function(data) { | |
// log data to the console so we can see | |
console.log(data); | |
writeTable(data.items); | |
// here we will handle errors and validation messages | |
}); | |
// stop the form from submitting the normal way and refreshing the page | |
event.preventDefault(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment