What is the best way to showcase search results using Bootstrap?

I'm currently in the process of developing a Spotify application. Upon executing a GET query for a track search, I aim to showcase the results as interactive buttons featuring the track name and artist. As the query can yield varying numbers of outcomes, how can I dynamically insert and remove these buttons? The search findings are in JSON format.

Implementation: Bootstrap, HTML, and JavaScript

function searchSpotify(track) {
    $.post(URL + "/search", { "pc": getCookie('pc'), "track": track }, function (data, status) {
    console.log("Searching for: " + track)
    if (status === "success") {
        console.log("Results found: " + data)                    
        document.getElementById('textSpace').innerHTML = data
        localStorage.setItem('searchResults', JSON.stringify(data));
    }
})
.fail(function (response, status) {
    console.log("No results found");
})

This code showcases the search findings structured in a similar manner to the example below.

{
    "artists":["Calvin Harris","Morgan Evans","Prince","Lil Peep","Ed Sheeran","Carly Rae Jepsen","Sixpence None The Richer","Soulja Boy","Calvin Harris","Chris Brown"],
    "names":["One Kiss (with Dua Lipa)","Kiss Somebody","Kiss","Kiss","Kiss Me","Call Me Maybe","Kiss Me","Kiss Me Thru The Phone","One Kiss (with Dua Lipa) - ZHU Remix","Kiss Kiss"],
    "ids":["7ef4DlsgrMEH11cDZd32M6","1mJMD1VIQ7jWTP9DK2zmY0","62LJFaYihsdVrrkgUOJC05","4J3FltfCktHfD9iPCneDGy","0Tel1fmuCxEFV6wBLXsEdk","3TGRqZ0a2l1LRblBkJoaDx","754kgU5rWscRTfvlsuEwFp","2q4rjDy9WhaN3o9MvDbO21","3aNt9AQw0JSY9dvCiPK1kF","4CweuuMMzi71pO0MSRgyaT"]
}

Answer №1

 
    (function musicButtons() {
        var content = {
            "artists": ["Calvin Harris", "Morgan Evans", "Prince", "Lil Peep", "Ed Sheeran", "Carly Rae Jepsen", "Sixpence None The Richer", "Soulja Boy", "Calvin Harris", "Chris Brown"],
            "names": ["One Kiss (with Dua Lipa)", "Kiss Somebody", "Kiss", "Kiss", "Kiss Me", "Call Me Maybe", "Kiss Me", "Kiss Me Thru The Phone", "One Kiss (with Dua Lipa) - ZHU Remix", "Kiss Kiss"],
            "ids": ["7ef4DlsgrMEH11cDZd32M6", "1mJMD1VIQ7jWTP9DK2zmY0", "62LJFaYihsdVrrkgUOJC05", "4J3FltfCktHfD9iPCneDGy", "0Tel1fmuCxEFV6wBLXsEdk", "3TGRqZ0a2l1LRblBkJoaDx", "754kgU5rWscRTfvlsuEwFp", "2q4rjDy9WhaN3o9MvDbO21", "3aNt9AQw0JSY9dvCiPK1kF", "4CweuuMMzi71pO0MSRgyaT"]
        }
        let htmlContent = "";
        for(let i = 0; i < content.artists.length; i++){
            htmlContent += '<button type="button" class="btn btn - primary">artists: ' + content.artists[i] 
                + ' song: ' + content.names + '</button>';
        }

        $('#theButtons').html(htmlContent);
    })();
<!DOCTYPE HTML>
<html>

<body>

<div id="theButtons">
</div>

</body>

</html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Embed this code into your functions as a .done action to complement the existing .fail. With jQuery, the data object is iterated through to create html elements, then inserted into the page via $('#theButtons').html(sHTML);.

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

The second jQueryUI datepicker instance flickers and vanishes when the show() function is triggered

I currently have two jQueryUI datepickers integrated into my webpage. The initialization code for both is as follows: jQuery("#departureDate").datepicker({ beforeShow: function() { getDatesForCalendar("outbound"); }, numberOfMonths: 3 ...

Guide to setting a generic key restriction on a function parameter

Today, I decided to have some coding fun and try creating a generic pushUnique function. This function is designed to check if a new object being added to an array is unique based on a key, and then push it if it meets the criteria. At this point, all I h ...

Ensuring proper alignment of images on image slider specifically for Chrome browser

While updating a website, I encountered an issue with the image slider displaying two images side-by-side. However, in Chrome, the images were not aligned properly as shown here: The website utilizes PHP and HTML to fetch data from a database and display ...

Customizing browser titles for various article pages on Joomla 3.2 for improved SEO performance

Is there a way to incorporate unique browser titles for various article pages? Additionally, I am seeking guidance on how to integrate distinct meta tags for different pages within a Joomla website... ...

How can I transform a collection of objects into an array using Javascript?

What would be the best way to convert this content into an array? https://i.sstatic.net/H6Fo9.png I have this: ...

Performing file downloads through AJAX in AngularJS

Recently, I developed an AngularJS program to facilitate file downloads from the server. Below is the code: HTML Code <a download="fullList.csv" ng-href="{{ fullListUrl }}" type="button" class="btn btn-success btn-xs exec-batch" ng-click="exportCSVBu ...

What Causes the Response to Vary in a Post Request?

Issue: When I use console.log(res.data), it shows different data compared to console.log(JSON.parse(res.request.response)). My Next.js application is sending a post request to an internal API. The response from the REST endpoint should contain a list obje ...

Embed a script tag in Capybara and pause execution until an asynchronous task is finished

Having trouble injecting a script in Capybara. Take a look at the code below: Capybara.register_driver :poltergeist do |app| Capybara::Poltergeist::Driver.new(app, :phantomjs_options => ['--debug=no', '--ignore-ssl-errors=yes' ...

Error encountered during the prerendering process on Vercel's Next.js build

While trying to compile my website on Vercel, I encountered a pre-rendering error during export. Does anyone know why this is happening and can provide assistance? Here is the link to my GitHub repository where all the code is stored: https://github.com/M ...

Angular dynamically selects a dropdown option when the page is loaded

Check out this dropdown example: <div class="col-md-6"> <div class="form-group> <label class="control-label">Role</label> < ...

Icon displayed on separate line

I'm currently working on displaying FontAwesome icons with the category names on WooCommerce WordPress products. While I've managed to get them to show on a separate page, I'm encountering an issue when trying to display them in the mega men ...

Align the drop-down caret to the right using Bootstrap 4.1

I am currently using Bootstrap 4.1 and I have a Navbar that triggers a Modal Dialog Box with tabs and a drop down menu containing an image icon. My goal is to make the "caret" or down arrow of the drop down menu appear on the right side of the image. To a ...

Am I on the right track with my service definition in Angular?

(function(){ angular.module('myApp',[]) })(); (function(){ angular.module('myApp.dashboard',[]) })(); (function(){ angular.module('myApp.value',[]) })(); (function(){ 'use strict'; angular.modu ...

"Exploring the process of transferring an ID from one service to another using the select feature in Angular

I need to store the ID I receive from one service into another using the select element. Here is my approach: <select class="form-control" id="select_fac" [(ngModel)]="rep.idfac"> <option selected disa ...

How to access localStorage within an AngularJS module

Upon successful login, I save the user's data in the localStorage and redirect them to the Dashboard. LoginCtrl: (function() { 'use strict'; angular.module('BlurAdmin.pages.login') .controller('LoginCtrl& ...

Understanding the purpose of the notched property in Material-UI

I am currently integrating Material-UI into a project and exploring their API. One thing that I find confusing is the notched property within the OutlineInput Component. <FormControl variant='outlined'> <OutlinedInput notched={false} ...

Filter an array containing objects within objects and use the reduce method to calculate the total value

Here is an array of objects that I'm working with: const data = [ { "order_id":38795, "order_type":"Music", "date":"2021-08-14", "name":"Concert ...

Is there a way to identify when a specific DIV element changes its dimensions without continuously polling for updates? In other words, I am looking for a method to

Running ads on my website has been great, but one of the ads keeps changing the dimensions of the DIV it's in, causing layout issues with other elements on the page. To solve this problem, I need to add an event listener to the specific DIV element t ...

Three.js fails to render Blender model

After creating a basic blender model, I exported it as a .json file using the three.js plugin. However, when attempting to import the file into my project, I encountered some difficulties. As file transfers are restricted through file://, I uploaded the f ...

Alert: It is not possible to update the React state on a component that is already unmounted after updating the context and switching to a different page

I am facing a challenge that requires your assistance In the /editpage, there is a changeProfile function that should be triggered upon clicking const appContext = useContext(AppContext); const [userLogin, setUserLogin] = appContext.userLogin; const [use ...