Reputation: 29
Hi how do I use jquery with AJAX to grab images from a JSON file and display it on my page? Here's my code.
function bookSearch(){
var search = document.getElementById('search').value;
//Results innerHTML is an empty string, so it would be a new search each time.
document.getElementById('results').innerHTML= ""
$.ajax ({
url: "https://www.googleapis.com/books/v1/volumes?q=" + search,
dataType: "json",
success: function(data){
var results= document.getElementById('results');
for(i = 0; i < data.items.length; i++){
results.innerHTML += "<span class='col-md-4'>" + data.items[i].volumeInfo.title + "</span>"
results.innerHTML += "<img class='col-md-4'>" + data.items[i].imageLinks.smallThumbnail + "</img>"
}
},
type: 'GET'
});
}
document.getElementById('button').addEventListener('click', bookSearch, false)
Upvotes: 0
Views: 2293
Reputation: 9928
You need to set the src
property of the image HTML element.
results.innerHTML += "<img class='col-md-4' src='" + data.items[i].volumeInfo.imageLinks.smallThumbnail + "'"
Following is a working implementation of the code. Also, note that i have manipulated the DOM using jquery.
$(document).ready(function()
function, so that an event handler can be registered when the DOM has completely loaded. $('#search').val();
method.$('#results').html('')
method to set the innerHTML.on
method, $("#button").on("click", bookSearch);
smallThumbnail
property should be accessed as data.items[i].volumeInfo.imageLinks.smallThumbnail
and not as data.items[i].imageLinks.smallThumbnail
$(document).ready(function(){
function bookSearch(){
var search = $('#search').val();
//Results innerHTML is an empty string, so it would be a new search each time.
document.getElementById('results').innerHTML= ""
$.ajax ({
url: "https://www.googleapis.com/books/v1/volumes?q=" + search,
dataType: "json",
success: function(data){
var innerHTML = "";
for(var i=0; i < data.items.length; i++){
if(data.items[i].volumeInfo.title && data.items[i].volumeInfo.imageLinks &&
data.items[i].volumeInfo.imageLinks.smallThumbnail){
innerHTML += "<span class='col-md-4' title='>" + data.items[i].volumeInfo.title + "'</span>" +
"<img class='col-md-4' src='" + data.items[i].volumeInfo.imageLinks.smallThumbnail + "'>";
}
}
$('#results').html(innerHTML);
},
type: 'GET'
});
}
$("#button").on("click", bookSearch);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" type="text"/>
<button id="button">image</button>
<div id="results"></div>
Upvotes: 5
Reputation: 61
I believe you are on the correct track. However the 'img' tag requires you to specify the 'src' to display the image.
I think this is what you are looking for:
for(i = 0; i < data.items.length; i++){
results.innerHTML += "<span class='col-md-4'>" + data.items[i].volumeInfo.title + "</span>"
results.innerHTML += "<img class='col-md-4' src='" + data.items[i].imageLinks.smallThumbnail + "'/>"
}
Upvotes: 2