Displaying images from JSON - javascript

Trying to display the cover art with the results. Something in the img src tag is causing the app not to load. If I just point the img to data.tracks[i].album.name (obviously not a real url, but enough to test if it's working) it pastes it in just fine, but the moment I change it to paste the url in place, it makes the whole app stop working.
$('#findTracks').click(function (e) {
e.preventDefault(); // override/don't submit form
$('#recommendations').empty();
var artist = $('#artist').val();
var userid = "";
var playlistid = "";
$.ajax({
url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
type: 'GET',
dataType: 'json',
success: function(data) {
if (data.tracks.length > 0) {
var tracksLength = data.tracks.length, html = '';
for (var i=0; i<tracksLength; i++) {
var href = '';
if (data.tracks[i].album.availability.territories.indexOf(' GB ') !== -1) { // data.tracks[i].href
href = data.tracks[i].href;
href = 'makeReq(\''+data.tracks[i].name + ' by '+data.tracks[i].artists[0].name+'\')';
html += '<li>' +data.tracks[i].name + ' by '+data.tracks[i].artists[0].name+ ' <img src="' +data.tracks[i].album.images[0].url+ '" />';html += '</li>';
html += '</li>';
}
}
$('#third').css('display', 'block');
$('#recommendations').append(html);
} else {
$('#recommendations').append('<li>No matches returned.</li>');
$('#third').css('display', 'none');
}
},
error: function(err) {
alert("The Spotify API failed to return a response.");
}
});
});
This is my first time ever coding in javascript so please go easy on me! lol
EDIT:
This seems to be running well! However, many of the songs do nothing when I click on them
For example, type "Don't Stop" and only "The Black Eyed Peas - Don’t Stop The Party" works out of the first ten...anybody know why?
also, anybody known why "if (data.tracks[i].album.availability.territories.indexOf(' GB ') !== -1)" is in there? If I take it out this all stops working...I am not in G.B.

If you look in the console you are getting the error
Uncaught TypeError: Cannot read property '0' of undefined
looking at the data the query returns we notice that data.tracks[i].album returns
{
"released": "2006",
"href": "spotify:album:2knAf4wg8Gff8q1bXiXCTz",
"name": "The Dutchess",
"availability": {
"territories": "MX"
}
}
there is no property images so when you call
data.tracks[i].album.images[0]
you get the undefined error, causing the script to halt execution.
I'm unfamiliar with the spootify api but taking a quick glance at the api theres the endpoint for get-album. Heres what I was able to come up with to get the album art
$.get("http://ws.spotify.com/search/1/track.json?q=Fergie",function(data){
var albumId = data.tracks[97].album.href.split(":")[2];
$.get("https://api.spotify.com/v1/albums/" + albumId,function(albumResponse){
var firstImage = albumResponse.images[0];
$('body').append($('<img/>',{
src : firstImage.url,
width : firstImage.width,
height : firstImage.height
}));
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body></body>
You should research more into how to get the album art since I'm unsure if this is the optimal solution.
The search endpoint you mentioned is different from the one your using.
One your using
url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
One you linked to
url: 'https://api.spotify.com/v1/search?q=' + artist + '&type=track,artist&market=GB',
Heres your solution with the change in endpoint
$('#findTracks').click(function(e) {
e.preventDefault(); // override/don't submit form
$('#recommendations').empty();
var artist = $('#artist').val();
var userid = "";
var playlistid = "";
$.ajax({
//url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
url: 'https://api.spotify.com/v1/search?q=' + artist + '&type=track,artist&market=GB',
type: 'GET',
dataType: 'json',
success: function(data) {
if (data.tracks.items.length > 0) {
data.tracks = data.tracks.items
data.artists = data.artists.items
var tracksLength = data.tracks.length,
html = '';
for (var i = 0; i < tracksLength; i++) {
var href = '';
href = data.tracks[i].href;
href = 'makeReq(\'' + data.tracks[i].name + ' by ' + data.tracks[i].artists[0].name + '\')';
html += '<li>' + data.tracks[i].name + ' by ' + data.tracks[i].artists[0].name + ' <img src="' + data.tracks[i].album.images[0].url + '" />';
html += '</li>';
html += '</li>';
}
$('#third').css('display', 'block');
$('#recommendations').append(html);
} else {
$('#recommendations').append('<li>No matches returned.</li>');
$('#third').css('display', 'none');
}
},
error: function(err) {
alert("The Spotify API failed to return a response.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Artist:
<input type="text" id="artist" />
<button id="findTracks">Find Tracks</button>
<div id="recommendations"></div>

Related

FCC wikipedia viewer not receiving data

I'm have some serious problems getting any response data through from the mediawiki api.
I'm trying to do the freecodecamp wikipedia viewer challenge and I'm coding it here:
https://codepen.io/dceaser334/pen/zpQXOJ
All i'm trying to do so far is GET the data and print it to the console using the following request:
$('.search-button').on('click', function() {
var searchInput = $('.search-input').val();
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=' + searchInput + '&format=json&callback=?', function(data) {
console.log(data);
});
});
All i'm trying to do so far is GET the data and print it to the console using the that request.
I'm getting this error in firefox:
Loading failed for the with source
“https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=jordan&format=json&callback=jQuery32105036538970753343_1518470620925&_=1518470620926”.
index.html:1
Nothing loads to the console and it seems like the request is blocked.
I've tried using origin=* which also makes no difference.
I'm a bit lost because this project has similar code for the GET request and works perfectly:
https://codepen.io/luckyguy73/pen/GqPzZO?editors=1010
$("#searchWiki").click(function(){
var q = document.getElementById("searchid").value;
$('#results').html('');
$.getJSON("https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=15&generator=search&origin=*&gsrsearch=" + q, function(data){
$('#results').append('<h2>Top 15 Wiki Search Results for "' + q + '"</h2>');
$.each(data.query.pages, function (i) {
$('#results').append("<p><a href='https://en.wikipedia.org/?curid=" + data.query.pages[i].pageid +
"' target='_blank'>" + data.query.pages[i].title + "</a></p>");
});
});
});
Any ideas on what I'm doing wrong here?
Thanks
I did it like this. Maybe you will be inspired by analyzing my code?
( function ( $ ) {
"use strict";
$(document).ready(function(){
function loadData() {
$(".information").text(""); // Reset data before new search.
$(function whiteFirst() {
const query = $(".wiki_query").val();
const myFirstWikiUrl = "https://en.wikipedia.org/w/api.php?action=opensearch&search=";
const mySecondWikiUrl = "&format=json&callback=wikiCallback";
const wikiUrl = myFirstWikiUrl + query + mySecondWikiUrl;
// MY WIKIPEDIA AJAX GOES HERE - TOP
const wikiRequestTimeout = setTimeout(function() {
$(".small-information").html("An error occurred! Application couldn't get Wikipedia resources!");
}, 5000); // This is 5 seconds!
$.ajax({
url: wikiUrl,
dataType: "jsonp",
type: "GET",
}).done(function(result) {
const itemsOne = [];
const itemsTwo = [];
const itemsThree = [];
$(result[1]).each(function(index, value) {
itemsOne.push(value);
});
$(result[2]).each(function(index, value) {
itemsTwo.push(value);
});
$(result[3]).each(function(index, value) {
itemsThree.push(value);
});
$(".information").hide();
$(".results").hide();
for (let i = 0; i < itemsOne.length; i++) {
$(".information").append("<a class='title' href=" + itemsThree[i] + " target='_blank'><div class='result'><p class='title' id='boldTitle'>" + itemsOne[i] + "</p><p>" + itemsTwo[i] + "</p></div></a>");
}
if (itemsOne.length === 0) {
$(".information").html("Nothing found!");
}
$(".results").show();
$("body,html").animate({
'scrollTop': $(".results").offset().top
}, 2000);
$(".information").fadeIn("slow");
clearTimeout(wikiRequestTimeout); // This will prevent timeout from happening!
});
// MY WIKIPEDIA AJAX GOES HERE - BOTTOM
});
return false;
};
$(".whiteButton").click(loadData);
$(".results").hide();
$(function() {
const offset = -50; // Optional offset
$(".back").click(function() {
$("html, body").animate({
scrollTop: $(".cover").offset().top + offset
}, 750);
});
});
});
} ( jQuery ) );

File browsing and omdb

I'm kinda new to php + javascript.
I have set up "cute file browser" to look at a shared folder on my computer.
it works fine displays all files & folders no problem.
Now im trying to use OMDB to search for movie posters and then display them for each movie name.
Currently it works but only with the first movie title. when inspecting the element in FF it does show all the other posters but only within the first
This is the code i made for the OMDB...
var filmName;
var realName;
filmName = finfo;
realName = filmName.split('.')[0];
var omdbUrl = "http://www.omdbapi.com/?t=" + realName;
$.ajax({
url: omdbUrl,
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//now json variable contains data in json format
//let's display a few items
document.getElementById("folders").innerHTML += "<img id='imgposter' class='imgPoster' src='" + json.Poster + "'></img>";
}
});
And this is the code for displaying my movie folders:
if(scannedFolders.length) {
scannedFolders.forEach(function(f) {
var itemsLength = f.items.length,
name = escapeHTML(f.name);
if(itemsLength) {
icon = '<span class="icon folder full"></span>';
}
if(itemsLength == 1) {
itemsLength += ' item';
}
else if(itemsLength > 1) {
itemsLength += ' items';
getPoster(name);
}
else {
itemsLength = 'Empty';
}
var folder = $('<li id="folders" class="folders"><span class="name">' + name + '</span> </li>');
folder.appendTo(fileList);
});
}
This is the error i get
As i said i am new here. if anyone could give me any tips would be great thanks

Append image in function jquery

Good evening.
I have this jquery code which allows me, once you press the Enter key, to post a comment.
Fattio that I run an append with the username and the content that the user wants to publish.
In addition to the username I would also like to "hang" the profile picture using their path. How do I post a photo?
Thanks for your help. Here's the code:
function commento_post(id_post)
{
$('.form-commento'+id_post).click(function ()
{
$('#ins_commento'+id_post).keydown(function (e)
{
var message = $("#commento"+id_post).val();
var username = $("#username").val();
var id_user = $("#id_user").val();
if(e.keyCode === 13)
{
$.ajax(
{
type: 'POST',
url: 'http://localhost/laravel/public/index.php/post/ins_commento',
data: { commento: message, id_post: id_post },
success: function(data)
{
$('#commento'+id_post).val('');
$('#commentscontainer'+id_post).append
(
/*$(".username-commento"+id_post).html
(*/
$('<a/>',
{
text : username, href : 'http://localhost/laravel/public/index.php/utente/'+id_user
}).css({'font-weight':'bold'})
//)
).append(' ').append(message).append($('<br/>'));
var el = $('#numero_commenti'+id_post);
var num = parseInt(el.text());
el.text(num + 1);
}
});
}
});
});
}
In your success function, you could simplify everything quite a bit in the following way while not using jQuery append so much, but just using a variable to store your code and then appending it in one go. This will allow you to append all sort of elements, it's easily parseable for the you and it reduces the amount of calls you have to make.
// Add whatever you want your final HTML to look like to this variable
var html = "<a href='http://localhost/laravel/public/index.php/utente/" + id_user + "' style='font-weight: bold;'>" + username + "</a>";
html += message;
// add an image
html += "<img src='path/to/image.jpg' />"
html += "<br />";
// append to code you constructed above in one go
$('#commentscontainer' + id_post).append(html);
Update
I amended an incorrect quote and changed + id_user + "to + id_user + "', which makes everything after it work.

Saving data to parse using javaScript SDK

Using parse.com and JavaScript SDK.
- Section one shows a list of objects
- Section two lets the user select one of those objects and add to a modal box
- Section three saves the data to parse
What I'm unable to work out is how I can save the section 1 item.badgename and item.category to parse.
I've tried adding myBadge.set("category", badgename.toString()); to section 3, but I get a undefined error. i'm not sure how to define this before trying to save.
Really need some help and an example to follow.
3 -Saves the badge details to parse
var MyBadge = Parse.Object.extend("myBadges");
var FriendRequest = Parse.Object.extend("FriendRequest");
var friendRequest = new FriendRequest();
friendRequest.id = window.selectedFriendRequestId;
var badgeselected = $('#badgeselect .go').attr("src");
$(document).ready(function() {
$("#send").click(function() {
var myBadge = new MyBadge();
var badgeselected = $('#badgeselect img').attr("src");
var BadgeSentTo = $('#selectFriend').val();
var categorySelected = $('#category').val();
var uploadercomment = $('#UploaderComment').val();
myBadge.set("BadgeName", badgeselected); //got this working using .set
myBadge.set("Comment", uploadercomment); //got this working using .set
myBadge.set("category", categorySelected);
myBadge.set("SentTo", new Parse.User({
id: BadgeSentTo
}));
myBadge.set("uploadedBy", Parse.User.current());
myBadge.save(null, {
success: function(results) {
console.log("Done");
//location.reload();
},
error: function(contact, error) {
// The save failed.
alert("Error: " + error.code + " " + error.message);
}
});
return false;
});
});
** 1- Returns results to the page for user to select**
var GlobalBadges = Parse.Object.extend("Global_Badges");
var query = new Parse.Query(GlobalBadges);
query.exists("Global_Badges_img");
query.find({
success: function(results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('Global_Badges_img'),
//friendRequestId: results[i].id,
badgename: results[i].get('BadgeName'),
category: results[i].get('category')
});
}
// TW: replaced dynamic HTML generation with wrapper DIV that contains IMG and name DIV
_.each(friends, function(item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div></div>');
wrapper.append('<img class="images BadgeImgOutline responsive-image" src="' + item.imageURL + '" />'+ '<br>');
wrapper.append('<div id="name"class="tag badgelabel" >'+ item.badgename + '</div>'+ '<br>');
wrapper.append('<div id="category" class="tag categorylabel" >'+ item.category + '</div>'+ '<br>'+ '<br>' );
$('#container').append(wrapper);
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
2 -Upon the user selecting an object from above, this adds the data to a modalbox
$(document).ready(function() {
$('.go img').css('cursor', 'pointer');
$('.go').on('click', 'img', function(e) {
$('.go img').removeClass('BadgeImgOutline');
$(this).parent().appendTo('#badgeselect');
$(this).addClass('BadgeImgOutlineSmall');
$('.go img').addClass('BadgeImgOutline');
$('#modal').reveal({
closeonbackgroundclick: true,
dismissmodalclass: 'close'
});
return false;
});
});
This was addressed by making the following changes.
- Taking the data from #badgeSelect not #category
- From section 3, the line var categorySelected = $('#category').val(); was changed to categorySelected = $('#badgeselect .categorylabel').text();
By taking the data from #badgeSelect it meant that the only data being available was that shown shown in the text box, instead of '#category'that returned all results.
The it was simply targeting the text correctly with the change to the var categorySelected

How to get specific entry with JS from a DB (JSON)

I'm trying to do something like a dictionary. The idea is there is a DB online. Someone can search for term and get the description from the db.
How it works:
1) whole terms from the db will be downloaded and compared with searchterm. each term has its specific ID. If the searchterm is the DB the ID will be saved.
2) The ID will be sent to the server with the DB and than it should receive the description
URL to get all Terms
http://s288617660.mialojamiento.es/api.php?rquest=terms
Url to get description
http://s288617660.mialojamiento.es/api.php?rquest=answers&param1=ID
Now this is my search function
<script>
getAllTerms();
function getAllTerms(){
var url = "http://s288617660.mialojamiento.es/api.php?rquest=terms";
$.get(url, function(data) {
localStorage.setItem("terms", JSON.stringify(data));
//alert(JSON.stringify(data));
}).done(function() { /*alert(localStorage.getItem("terms"));*/ })
.fail(function() { alert("error"); })
.always(function() { /*alert("finished");*/ });
}
function findTerm(){
var content = $("#SearchTerm").val();
//alert(content);
var id = 0;
var data = JSON.parse(localStorage.getItem("terms"));
$.each(data, function(index, term) {
//alert("My content " + content + ", term " + term.name);
if(content == term.name){
id = term.id_term;
}
});
//--------------my try to request the description
var url_answers = "http://s288617660.mialojamiento.es/api.php?rquest=answers&param1="+id;
//alert(url_answers);
var answer = "";
$.get(url_answers, function(data2) {
localStorage.setItem("answer", JSON.stringify(data2));
$.each(data2, function(index, object) {
answer = object.description+object.id_answer;
});
//-----------------end of my try
//alert(id);
var htmlStr = "";
if(parseInt(id) > 0){
//i found the term
localStorage.setItem("idterm",id);
htmlStr = "<li>" + content + "- id: " + id + answer + "</li>"
}else{
//not found
htmlStr = "<li>Term not found</li>"
}
$('#SearchList').empty();
$('#SearchList').append(htmlStr);
$('#SearchList').listview("refresh");
}
</script>
The ID request just works fine but not the description request. Why?
By the way: it's a android phonegap project

Categories