jQuery - Getting certain XML not working - javascript

Let's say I have an XML like this: http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=b25b959554ed76058ac220b7b2e0a026&track=Just%20for%20Me&artist=Hinoi%20Team
I'm trying to get the name of the track and it's not working: I do this:
$.ajax({
type: "GET",
url: "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=b25b959554ed76058ac220b7b2e0a026&track="+yourTrack+"&artist="+yourArtist,
dataType: "xml",
success: function(xml) {
$(".loading").css("display", "none");
$(xml).find('track').each(function(){
var id = $(this).find('id').text();
console.log("Success!");
var song = $(this).find('track > name').text();
var name = $(this).find('artist name').text();
var album = $(this).find('album title').text();
$("#more").append("\nSong: " + song);
$("#more").append("\nArtist: " + name);
$("#more").append("\nAlbum: " + album);
$("#more").append("\n\nlast.fm ID: " + id);
});
}
});
and the result is this:
Song:
Artist: Hinoi Team
Album: Super Euro Party
last.fm ID: 43135480
Help?

The selector in this line isn't right:
var song = $(this).find('track > name').text();
$(this) is a <track> element. You are looking for another <track> element inside of it, which isn't what you need. You are looking for the <name>, so use this instead:
var song = $('> name', this).text();

Related

Fetching data from API and displaying as Name and website link

I am trying to fetch data from the API and display them in format Name + clickable website link.
I was able to display data but the link is represented as text rather than hyperlink.
There is my Ajax script:
$(function() {
$.ajax({
url: "url",
type: "get",
dataType: "json",
success: function(data) {
console.log(data.name);
for (i = 0; data.length; i++) {
name = data[i].name;
web_pages = data[i].web_pages;
var link = document.createElement('a');
link.setAttribute('href', web_pages);
link.innerHTML = web_pages;
var paragraph = $("<p />", {
text: name + " " + link
});
$("#display-resources").append(paragraph);
}
}
});
});
It's because you're inserting the link as text (string). Try this instead
var paragraph = $("<p />", { text: name + " " }).append(link)

Show image based on jQuery variable

I have the following code reading an XML file and creating variables from some of the values. This is my jQuery:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'https://status.clook.net/xml/status/harvey.xml',
dataType: 'xml',
success: function(xml){
var http = $(xml).find('http').text();
var ftp = $(xml).find('ftp').text();
var mysql = $(xml).find('mysql').text();
var pop = $(xml).find('pop').text();
var imap = $(xml).find('imap').text();
var smtp = $(xml).find('smtp').text();
var load = $(xml).find('load').text();
$('.http').html(http);
$('.ftp').html(ftp);
}
});
$.ajax({
type: 'GET',
url: 'https://status.clook.net/xml/status/email01.xml',
dataType: 'xml',
success: function(xml){
var ehttp = $(xml).find('http').text();
var eftp = $(xml).find('ftp').text();
var emysql = $(xml).find('mysql').text();
var epop = $(xml).find('pop').text();
var eimap = $(xml).find('imap').text();
var esmtp = $(xml).find('smtp').text();
var eload = $(xml).find('load').text();
$('.ehttp').html(ehttp);
$('.eftp').html(eftp);
}
});
});
This is then being used with the following HTML:
<div class="container">
<h3>Server Status Widget</h3>
<h4>Hosting Server</h4>
<p>
<strong>HTTP: </strong>
<span class="http"></span>
</p>
<p>
<strong>FTP: </strong>
<span class="ftp"></span>
</p>
<h4>Email Server</h4>
<p>
<strong>HTTP: </strong>
<span class="ehttp"></span>
</p>
<p>
<strong>FTP: </strong>
<span class="eftp"></span>
</p>
</div>
What I would like to do now is instead of outputting the variable, show an image based on the variable value. I would like to check if the variable value is OK, and if so display an image in the span, and then if the variable is anything other to show another image.
For instance if the variable http has the value OK, in span .http to show allgood.jpg. If the variable value is anything other than OK to show notgood.jpg.
if (ehttp == "ok") {
var imgsrc = '/images/' + ehttp + '.png';
var img = document.createElement("img");
var img.src = imgsrc;
var target = document.querySelector('.ehttp');
target.appendChild(img);
}
From what I understand of your objective, I'd do something like that.
You could write something like this, with a generalised showResult() function to avoid duplication of code.
$(document).ready(function() {
// Fixed data (adapt as necessary)
var OkText = 'OK';
var paths = {
'goodHttp': '/path/to/good/http/image/',
'badHttp': '/path/to/bad/http/image/',
'goodFtp': '/path/to/good/ftp/image/',
'badFtp': '/path/to/bad/ftp/image/'
};
// Generalised utility function
function showResult(containers, xml) {
var httpText = $(xml).find('http').text();
var ftpText = $(xml).find('ftp').text();
if(httpText === OkText) {
containers.http.html('<img src="' + paths.goodHttp + '"/>');
} else {
containers.http.html('<img src="' + paths.badHttp + '"/>');
}
if(ftpText === OkText) {
containers.ftp.html('<img src="' + paths.goodFtp + '"/>');
} else {
containers.ftp.html('<img src="' + paths.badFtp + '"/>');
}
}
// AJAX
$.ajax({
'url': 'https://status.clook.net/xml/status/harvey.xml',
'dataType': 'xml',
}).then(showResult.bind({
'http': $("span.http"),
'ftp': $("span.ftp")
}));
$.ajax({
'url': 'https://status.clook.net/xml/status/email01.xml',
'dataType': 'xml',
}).then(showResult.bind({
'http': $("span.ehttp"),
'ftp': $("span.eftp")
}));
});
Note the use of Function.prototype.bind() to cater for the differences between the two calls.
A better approach might be to hard code the <img> elements then change their src properties.

insert received information into table on html

I am doing on a instagram api, and I get information from server including user profiles and two more kinds. I want to put the information in a table on html. Each row is related to a username(since I searched for username), and there are profiles and two more things on each row. I am a little confused about how to do that.
here is my code:
var searchUsers = function(query,count){
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
data: {
q: query,
count: count,
access_token: access_token,
},
url: "https://api.instagram.com/v1/users/search",
success: function(data) {
// placing the images on the page
console.log(data);
if (data.data.length>0){
var resultShow = $("#users_result");
for (var i in data.data){
resultShow.append("<img src='" + data.data[i].profile_picture + "'></img>");
// var username = "https://www.instagram.com/"+ data.data[i].username;
// console.log(username);
resultShow.append("<a target='_blank' href = 'https://www.instagram.com/"+data.data[i].username+"'>user profile</a>");
// var id = data.data[i].id;
// console.log(id);
$.ajax({
url: 'https://api.instagram.com/v1/users/' + data.data[i].id + '/media/recent/',
type: "GET",
dataType: "jsonp",
data: {access_token: access_token},
success: function(data2){
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
},
error: function(data2){
console.log(data2);
}
});
}
} else {
resultShow.html("Noting found!");
}
},
error: function(data){
console.log(data);
}
});
};
You can change almost any value in a page using the innerHTML property.
Ex:document.getElementById("demo").innerHTML = "Paragraph changed!";
http://jsfiddle.net/blazeeboy/fNPvf/
To change the values inside a table, just assign an ID to it and change with your Javascript function.
In your case, I would suggest inserting any Javascript parameter between line 31 and 32.
success: function(data2){
var title = document.getElementById('title');
var username = "https://www.instagram.com/"+ data.data[i].username;
title.innerHTML = username;
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
}
It will write the username into the table with id "title", if you need more than one table value, you'll need to make a array and use the for loop to insert an specific value into a specific table, tr, etc... id
success: function(data2){
//tableids are the ids of each table row or column in the order you wanna write them
var tableids = ['0', '1', '2'];//starting at 0
var username = "https://www.instagram.com/"+ data.data[i].username;
var title = document.getElementById(tableids[i]);
title.innerHTML = username;
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
}
Hope it was clear enough

couchdDB dbroot issue

I am using couchdb. I am new to it. I don't know what to have in dbroot value in place of "db/". I have taken this code from one of coucdb tutorial.
Thanks in advance for your help.
//Use a namespace to protect the scope of function and variable names
var poq = {
//Some variables global to the local namespace ("poq")
root: "http://localhost:5984/",
dbroot: "db/",
max_quotes: 6,
//Invoked when the HTML page is first loaded
loadPage: function()
{
var six_latest = poq.root + "poquotes/_design/document/_view/by_year?&limit="
+ poq.max_quotes + "&descending=true&callback=?";
$.getJSON(six_latest, poq.handleMainQuotes);
$('#donewquote').click(function() {
var db_link = poq.dbroot + "poquotes";
var record = {
"type": "quote",
"author": $("#author").val(),
"text": $("#text").val(),
"work": {
"title": $("#title").val(),
"link": $("#link").val(),
"year": parseInt($("#year").val())
}
};
$.ajax({
url : db_link,
data : JSON.stringify(record),
contentType : "application/json",
type : 'POST',
processData : false,
dataType : "json",
success : function(resp) {
alert("New document created: " + JSON.stringify(resp));
}
});
return false;
});
//Set up the collapsible form for adding new quotes
$('#popup').click(function(){
$("#newquote").slideToggle();
});
//Start out with the create quote form collapsed
$("#newquote").slideToggle();
},
//Invoked with the result of the AJAX call to load quote documents
handleMainQuotes: function(json)
{
//Load up to six records, as available
quote_count = Math.min(poq.max_quotes, json["total_rows"])
for (var i=0; i<quote_count; i++) {
var doc = json["rows"][i]["value"]
var year = doc["work"]["year"].toString()
var title = doc["work"]["title"].toString()
var link = doc["work"]["link"].toString()
//Create an HTML snippet from the fields of each quote document
qblock = $("<div class='span4 featured-quote'></div>")
.append("<h2>" + doc["author"] + "</h2>")
.append("<p style='font-size: 80%; height: 8em;'>" + doc["text"] + "</p>")
.append("<p>" + year + "</p>")
.append("<p><a href='" + link + "'>" + title + "</a></p>")
.append("<p><a class='btn' href='#'>View details ยป</a></p>")
//jQuery's eq selector to find the target div corresponding to the loop index
$('div.featured-quote:eq(' + i.toString() + ')').replaceWith(qblock);
}
},
}
Looks like dbroot here is meant to be the name of your database. If you haven't created a database yet, you can do so with:
curl -X PUT http://localhost:5984/mynewdatabase
Being new to CouchDB I recommend you start with The Definitive Guide (http://guide.couchdb.org)

jQuery - Getting certain tags in XML tree

Let's say I have an XML like this: http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=b25b959554ed76058ac220b7b2e0a026&track=Just%20for%20Me&artist=Hinoi%20Team
I want to get the <name> inside of the <artist> branch. However there are other tags named <name> in XML as well. How do i target the one inside <artist> specifically?
Here's what I am using:
$.ajax({
type: "GET",
url: "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=b25b959554ed76058ac220b7b2e0a026&track="+yourTrack+"&artist="+yourArtist,
dataType: "xml",
success: function(xml) {
$(".loading").css("display", "none");
$(xml).find('track').each(function(){
var id = $(this).attr('id');
console.log("Success!");
var name = $(this).find('name').text();
$("#more").append("Listing results...\n");
$("#more").append("Name: " + name);
});
}
});
Since name is a direct child of artist, you can use > to get the child:
var name = $(this).find('artist > name').text();
Or, since there is no other name in artist:
var name = $(this).find('artist name').text();

Categories

Resources