I am using google book api for ISBN and I am able to get data. Now I want to attach that data into a form. I am not able to that. This is my Jquery Code
$(document).ready(function(){
$('#submitCode').click(function(){
var x;
var isbn = $('#isbn').val();
var xmlhttp = new XMLHttpRequest();
var url = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn;
xmlhttp.onreadystatechange = function() {
/*<![CDATA[*/
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
x = JSON.parse(xmlhttp.responseText);
callback(x);
}/*]]>*/
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function callback(x) {
alert(JSON.stringify(x));
console.log(x);
};
});
});
My HTML code
<div class="input-field col s6 m6">
<input id="author" name="author" th:field="*{author}" type="text" class="validate" />
<label for="author">Author</label>
</div>
<div class="input-field col s6 m6">
<input id="title" name="title" th:field="*{title}" type="text" class="validate" />
<label for="title">Title</label>
</div>
How should I attach author data and title into the form in Thymeleaf?
If you've been able to retrieve the data already, you should only need to update the DOM using $('#id').val(value)
. I did a bit of digging, and it looks like your API returns the title
and authors
like this, hence the use of json.items[0].volumeInfo
in the new callback code.
{
"items": [{
"volumeInfo": {
"title": "Example Title",
"subtitle": "Example Subtitle",
"authors": [ "Example Author" ]
}
}]
}
$(document).ready(function() {
$('#submitCode').click(function() {
var x;
var isbn = $('#isbn').val();
var xmlhttp = new XMLHttpRequest();
var url = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn;
xmlhttp.onreadystatechange = function() {
/*<![CDATA[*/
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
x = JSON.parse(xmlhttp.responseText);
callback(x);
} /*]]>*/
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function callback (json) {
var book = json.items[0].volumeInfo
$('#author').val(book.authors.join('; '))
$('#title').val(book.title)
};
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input id="isbn" type="text" value="1904764827"/>ISBN</label>
<div class="input-field col s6 m6">
<input id="author" name="author" th:field="*{author}" type="text" class="validate" />
<label for="author">Author</label>
</div>
<div class="input-field col s6 m6">
<input id="title" name="title" th:field="*{title}" type="text" class="validate" />
<label for="title">Title</label>
</div>
<button id="submitCode">Submit</button>