Trying to learn how to use APIs. I’m having some difficulty. I’m trying to get the results that a user searches for to be displayed on my page as thumbnails. I keep getting a 400 Error with my current code. If you’re able to spot my mistakes, please help. Thanks.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="script.js"></script> <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="top">
<h1>Spotify Song Search</h1>
<form>
<input type="search" placeholder="Search for a album or band" id="song">
<button type="submit" id="search">Search</button>
</form>
</div>
<div id="music">
</div>
</body>
</html>
JavaScript
$(document).ready(function() {
$('form').submit(function(evt) {
evt.preventDefault();
var $searchField = $('#song');
var spotifyAPI = "https://api.spotify.com/v1/search" // needs end point
var albums = $searchField.val();// Specifies type of user info to be retrieved and sent to Spotify API
var spotifyOptions = {
"type": "album",
"q": albums,
"limit": "limit"
}; // Requests data from spotify API. Must be a JavaScript Object
function displayAlbums(data){
var albumHTML = '<ul>'; // Opening ul tag to hold a single album result
$.each(data.albums.items, function(i, album){
albumHTML += '<div class="album" album-id="' + index + '">';
albumHTML += '<li>'; // You may need to use bootstrap to style array items correctly
albumHTML += '<a href="#">';
albumHTML += '<img src="' + album.images[0].url + '" alt="' + album.artists[1].name + '">';
albumHTML += '</a>';
albumHTML += '</li>';
albumHTML += '</div>';
return albumHTML;
});
albumHTML += '</ul>';
$('#music').html(albumHTML);
};
$.getJSON(spotifyAPI, spotifyOptions, displayAlbums); // Currently, these are only placeholders. The variables inserted as arguments have not been defined as variables
});
});