Utilize the Spotify API to discover tracks by including the album title and artist's name in the search

Currently working on a project that involves searching for a music track on Spotify. The idea is to input the track name in the text area and generate a list of matching Track IDs along with Artist Names, Album Names, and Artwork. I have made some progress with the code but I am stuck at retrieving the Album Name, Album Image, and Artist Name.

For example: If the track is "All of Me", the result should show: Artist: John Legend Track ID: 3U4isOIWM3VvDubwSI3y7a

This would be displayed as the first result...

http://jsfiddle.net/61f64ccq/2/

I also updated this part:

http://jsfiddle.net/UT7bQ/212/ {{name}} - {{this.artists.name}} I am trying to implement Handlebar.js to extract the artist's name from the .JSON data...

Below is the initial example....

Using pure JS / Handlebar.js and HTML5.... Any assistance would be appreciated... I tried using {{artists.name}} but it didn't work...

<div class="container">
<h1>Search for a Track - Spotify</h1>
<form id="search-form">
<input type="text" id="query" value="" class="form-control" />
<input type="submit" id="search" class="btn btn-primary" value="Search" />
</form>
<div id="results"></div>
</div>
<script id="results-template" type="text/x-handlebars-template">
{{#each tracks.items}}
<div >{{id}} -         
<br /> {{name}} <br/></div>
// Issue - Image
<div style="border:1px solid red; background-image:url({{images.2.url}})" data-album-id="{{id}}" class="cover"></div>
// Issue - Artist Name and Album Name
<div style="border:1px solid green; "> Artist name = {  } -  Album name = { } </div>

Javascript snippet -

<script>
var templateSource = document.getElementById('results-template').innerHTML,
template = Handlebars.compile(templateSource),
resultsPlaceholder = document.getElementById('results'),
playingCssClass = 'playing',
audioObject = null;
var fetchTracks = function (albumId, callback) {
$.ajax({
url: 'https://api.spotify.com/v1/albums/' + albumId,
success: function (response) {
callback(response);
}
});
};
var searchAlbums = function (query) {
$.ajax({
url: 'https://api.spotify.com/v1/search',
data: {
q: query,
type: 'track'
// Gets the track - search query
},
success: function (response) {
resultsPlaceholder.innerHTML = template(response);
}
});
};
// This was for playing the Track in your window...  Not working in the Track format...
results.addEventListener('click', function (e) {
var target = e.target;
if (target !== null && target.classList.contains('cover')) {
if (target.classList.contains(playingCssClass)) {
audioObject.pause();
} else {
if (audioObject) {
audioObject.pause();
}
fetchTracks(target.getAttribute('data-album-id'), function (data) {
audioObject = new Audio(data.tracks.items[0].preview_url);
audioObject.play();
target.classList.add(playingCssClass);
audioObject.addEventListener('ended', function () {
target.classList.remove(playingCssClass);
});
audioObject.addEventListener('pause', function () {
target.classList.remove(playingCssClass);
});
});
}
}
});
document.getElementById('search-form').addEventListener('submit', function (e) {
e.preventDefault();
searchAlbums(document.getElementById('query').value);
}, false);
</script>

Thank you, Simon

Answer №1

Check out the changes I made and added a Fiddle example - showcasing how to use Handlebars to get Album information in the correct format: Image / Artist, Album Type, and Album Name. Hopefully this will be helpful to others.

http://jsfiddle.net/61f64ccq/4/

<script id="results-template" type="text/x-handlebars-template">
{{#each tracks.items}}
<div >{{id}} -         
<br /> {{name}} <br/></div>
<div style="border:1px solid red; background-image:url({{album.images.2.url}})" data-album-id="{{id}}" class="cover"></div>
<div style="border:1px solid green; "> Artist name = {{artists.0.name}} </div>
<div style="border:1px solid green; "> Album Type = {{album.album_type}} </div>
<div style="border:1px solid green; "> Album name = {{album.name}} </div>
{{/each}}
</script>

Many thanks to everyone who has taken a look at this - the issue has been resolved. Cheers, Simon

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are your thoughts on combining a JSON object with HTML?

When using ASP.NET MVC, it is possible to return a JSONResult. return JSON(new { View = RenderViewAsString("MyView", model), wasSuccessful = true}) This approach combines HTML and data in a single JSON object. The goal is to utilize strongly typed HtmlHe ...

Data extracted from the range selector

Is there a way to take values and use them for hiding or displaying certain divs? I have been using jQuery Simple Slider for this purpose. I attempted the following code, but it did not work well. I want the div with id "3" to be visible when the slider ...

Whenever I attempt to incorporate the 'var' keyword within a for loop alongside setTimeOut, I encounter unusual output

Here's the code snippet I'm working with: for (var i = 1; i <= 5; i++) { setTimeout(function () { console.log(i); }, 1000); } I'm confused about the output of this code. When I run it, I see the number 6 printed in the c ...

Tips for coordinating the execution of 2 async.waterfalls in Node.js

I have a series of read commands that need to be executed in sequence. If any of them fail, the processing stops. The array readCommands contains functions for reading... async.waterfall(readCommands, function(err) { if (err) { console.log(e ...

Creating a button that redirects to an external link in CodeIgniter:

Hello everyone, I'm new here and I could really use some assistance with a problem. I am trying to link the button labeled 'lihat rincian' and each row of tables to redirect to an external link like Here's a snapshot of my datatables ...

Exploring the method to reveal the password hidden field in MVC by utilizing the Html helper

@Html.Password("password", null, new { @class = "form-control frmField", placeholder = "Password" }) I want to incorporate a button that when clicked will make the password visible. I know this can be achieved using jQuery or Javascript, but I am unsure h ...

Establishing a small boutique utilizing Vue.observable for property getters

I am currently importing the createStore function into a store.js file and passing an object with state properties and mutation functions as an argument, which is working well. createStore.js import Vue from 'vue' function createStore({ state, ...

Error encountered: DataTable - Unable to retrieve the 'length' property of a null value

I am currently using a datatable in my project: function drawRadnici() { $('#tableradnici').dataTable({ "ajax": { "url": 'track_radnici.php', "type": 'POST' ...

Matching Tables with JavaScript and JSON

After hours of coding, I'm stuck on a simple task and could really use some assistance. The "users" object contains user account information, with the function "get" meant to retrieve matching objects from this array. var users = [ { name ...

Angular: The Ultimate Guide to Reloading a Specific Section of HTML (Form/Div/Table)

On my create operation page, I have a form with two fields. When I reload the page using window.reload in code, I can see updates in the form. However, I want to trigger a refresh on the form by clicking a button. I need help writing a function that can r ...

Is it possible to determine the outcome of a JavaScript function using Python?

I am currently in the process of creating a web crawler. Extracting links from HTML is simple, but finding links that are generated by JavaScript proves to be more challenging for me. Is there a way to access the JavaScript output in order to determine w ...

NextJS - The server attempted to execute the find() function, which is only available on the client side

When attempting to utilize the .find method within the server component, I encounter an error. export async function TransactionList() { const transactions = await fetch('/transactions'); return ( <ul> {transactions.m ...

What is the best way to accurately determine the height and offset values of an element while utilizing ng-repeat?

My objective is to determine the offset and height of list items. Once I have those values, I trigger a function in a parent directive. Ultimately, this will involve transitioning elements in and out as they come into view. Issue: Due to the use of ng-rep ...

VueJS, when used in conjunction with Vuetify, might require an extra loader to handle scoped css

While attempting to compile my VueJS code using webpack, I encountered an error with the following code: <template> <v-app-bar app color="blue" flat height="100px"> <v-img class="mx-2" contain max-height="80" m ...

swapping out an external CSS file in React for a new CSS file

My React app is quite large and includes four main CSS files (darkLTR, lightLTR, darkRTL, lightRTL), which may not be the most efficient setup. The templates were provided by my boss, and I was instructed to use them instead of Material UI, which I initial ...

Issues with the Winston transport for Loggly are causing inconsistent performance

I have implemented Winston with 3 transports: Console, File, and Loggly (using https://github.com/loggly/winston-loggly-bulk). While the Console and File transports are functioning properly, I am facing an issue with the Loggly transport. It only logs my ...

Effective Strategies for Preserving Form Input Values during Validation Failure in Spring MVC

I am currently working on validating user input, and I want the user's input fields to be retained in case of any validation errors. This is how I have set up my input fields: <form:input path="firstName" class="text short" id="firstName" value=" ...

Tips for refreshing the page without losing the values of variables

In my simulation.jsp file, I have the following code that retrieves simulation data from a struts2 action: $(document).ready(function() { var data='<s:property escape="false" value="simInfos" />'; } Once I perform the simulation with this ...

Struggling to dynamically create form controls within Angular forms and receiving the following error in the console: "TypeError: feature_r5.get is not a function"

When I click a button in my Angular v14 HTML template, I am trying to dynamically generate form controls and although I am able to generate them, an error is popping up in the console. ERROR TypeError: feature_r5.get is not a function at PostAdvComponent_ ...

Connecting Next.js to a Database: A Step-by-Step Guide

I am interested in developing an application similar to Samsung Health that will involve heavy querying on a database. I am unsure whether it would be more beneficial to create a custom server using Node.js (with Express.js) instead of using the integrate ...