How to add and if condition into an append() with jQuery - javascript

I am finishing up a TwitchTV project but have been struggling to figure out how to append some code with jQuery. This code needs to check the API to see if a user is streaming or not, then, depending on if he or she is or not, append information to an already dynamic, jQuery produced html.
Take a look at my JavaScript code. Right now, under the “status” row, you will see each user has info. If the user is offline, I would simply like to have the html read “offline.” If the user is online, I would like it to read "Online: " plus a short description of what the channel is about (the stream information is stored in a variable called “stream,” and the short description is stored in a variable called “statusWhat”).
I’m sorry if that is a bit confusing. I think seeing the code will make things clear: https://codepen.io/JayDevelopment/pen/bMKrLK 1
$(function() {
var twitchers = [
"ESL_SC2",
"OgamingSC2",
"cretetion",
"storbeck",
"habathcx",
"RobotCaleb",
"noobs2ninjas"
];
//FREECODECAMP STREAM INFO AND API CALL
var url =
"https://api.twitch.tv/kraken/streams/freecodecamp?client_id=jjqkn1xu4g4rx7d3e1o5refrmw5bhd";
$.getJSON(url, function(data) {
if (data.stream === null) {
$("#fccStatus").html("OFFLINE");
} else {
$("#fccStatus").html("FreeCodeCamp is ONLINE");
}
$('#fccGame').html()
});
for (var i = 0; i < twitchers.length; i++) {
$.ajax({
type: "GET",
url: "https://api.twitch.tv/kraken/channels/" +
twitchers[i] +
"?client_id=jjqkn1xu4g4rx7d3e1o5refrmw5bhd",
success: function(dataFor) {
$.getJSON(
"https://api.twitch.tv/kraken/streams/" +
dataFor.name +
"?client_id=jjqkn1xu4g4rx7d3e1o5refrmw5bhd").done(function(data2) {
var name = dataFor.name;
var logo = dataFor.logo;
var statusWhat = dataFor.status;
var stream = data2.stream;
$('#info').append('<div class="row block">' +
'<div class="col-sm">' +
'<h1>' + '<img src=' + logo + '>' + '</h1>' +
'</div>' +
'<div class="col-sm">' +
'<h1>' + name + '</h1>' +
'</div>' +
'<div class="col-sm" id="change">' +
'<a href="https://www.twitch.tv/' + name + '"' + ' target="blank">' +
'<h1 id="status">' + stream + ': ' + statusWhat + '</h1>' +
'</a></div></div></div>')
/* if (stream === null) {
$("#status").append('OFFLINE');
} else {
$("#status").append('ONLINE: ' + statusWhat);
} */
}
);
},
error: function(error) {
$("#logo").append('<img src=' + '#' + '>' + "<br>");
$("#name").append('Invalid' + "<br>");
$('#status').append('Not found');
}
});
}
});

You can do it when you assign to the stream variable:
if (data2.stream) {
stream = data2.stream + " ONLINE: " + statusWhat;
} else {
stream = "OFFLINE";
}

Related

Can't figure out how to accurately make two API Calls

I'm working on a Twitch.tv app as part of the FCC course. I'm near the finish line but I'm struggling to get the logo for each user. To explain, there's two different links for the API where I can get data: Streams & Channels.
If I use the streams link I can only get the logo if the user is online (which isn't really any good), where as with Channel I can get it regardless. To get what's streaming though, I really need to use the Stream link. The outcome then I guess, is I need to use both.
I've tried a variety of ways to make one call to streams and one to channels for the logo with a load of different results and I really can't figure it out. The latest way I've tried (below) gets me logos but not the correct stream/streamer data. I'm guessing the issue is how I'm nesting the calls within one another, but I can't figure out the proper way to do it.
Would appreciate any help anyone can give. Here's my CodePen where you can see the full code.
function apicall(streamer) {
$.getJSON('https://api.twitch.tv/kraken/streams/' + streamer, function(a) {
if (a.stream == null) {
stateclass = 'bg-danger';
game = 'Offline';
status = '';
url = '';
} else {
stateclass = 'bg-success';
game = a.stream.game + ': ';
status = a.stream.channel.status;
url = '<a target="_blank" href="' + a.stream.channel.url + '">';
}
who = streamer;
$.getJSON('https://api.twitch.tv/kraken/channels/' + streamer, function(b) {
logo = b.logo;
console.log(logo);
html += '<div class ="row ' + stateclass + '"><div class="col-xs-2"><img src="' + logo + '"></div><div class="col-xs-4">' + who + '</div>' + '<div class="col-xs-6">' + url + game + status + '</a></div></div>';
$(".options").html(html);
});
});
}
See jQuery.when().
function apicall(streamer) {
var streamsReq = $.getJSON('https://api.twitch.tv/kraken/streams/' + streamer);
var channelsReq = $.getJSON('https://api.twitch.tv/kraken/channels/' + streamer);
return $.when(streamsReq, channelsReq).done(function (streams, channels) {
var stateclass, link, html = '';
if (streams.stream && streams.stream.cannel) {
stateclass = 'bg-success';
link = '<a target="_blank" href="' + streams.stream.channel.url + '">' +
streams.stream.game + ': ' + streams.stream.channel.status + '</a>';
} else {
stateclass = 'bg-danger';
link = 'Offline';
}
html += '<div class ="row ' + stateclass + '">';
html += '<div class="col-xs-2"><img src="' + channels.logo + '"></div>';
html += '<div class="col-xs-4">' + streamer + '</div>';
html += '<div class="col-xs-6">' + link + '</div>';
html += '</div>';
$(".options").html(html);
}).fail(function () {
// add error handling
});
}

Get Youtube and Vimeo thumbnails using ID on mobile

I am trying to get the thumbnails to display in a list
I have a database where the video name, type (video provider: youtube or vimeo), and video id, but the thumbnails are not displaying at all. I am doing this inside a loop, i.e, writing the HTML doc in a for loop to get the whole list from the database. I did a lot of research but it is still not working. Any idea why?
here is a portion of the code:
if (resp[0].recstatus != "NOTFOUND") {
for (var i = 0; i < resp.length; i++) {
p_str_li += "<li onclick=\"app.frmvideoGalleryService.viewModel.onVListClick('" + resp[i].drill_id + "')\" id='vid1" + i + "' class='videoPreview'>"
p_str_li += " <div id='vid2" + i + "' class='vid_thumb'>"
p_str_li += " <a id='vid3" + i + "' >"
p_str_li += " <img id='vid4" + i + "' src='styles/images/placeholders/thumbnail.jpg' alt='commentPic'>"
if (resp[i].video_type == 'VIMEO') {
$.ajax({
type: 'GET',
url: 'http://vimeo.com/api/v2/video/' + resp[i].video_id + '.json',
async: true,
jsonp: 'callback',
dataType: 'jsonp',
success: function (data) {
thumbnail_src = data[0].thumbnail_medium;
$('#vid4' + i).attr('src', thumbnail_src);
}
});
}
else if (resp[i].video_type == 'YOUTUBE') {
var thumbnail_src = 'http://i2.ytimg.com/vi/' + resp[i].video_id + '/hqdefault.jpg';
$('#vid4' + i).attr('src', thumbnail_src);
}
else {
$('#vid4' + i).attr('src', 'styles/images/placeholders/thumbnail.jpg');
}
p_str_li += " </a>"
p_str_li += " </div>"
}
}
Check these solutions:
Youtube: http://salman-w.blogspot.it/2010/01/retrieve-youtube-video-title.html
Vimeo: Dynamically get thumbnails and titles of vimeo videos [SOLVED!]

Retrieve Flickr photo title AND description using jQuery

Annoyingly, the FlickrAPI provides the title and description of a photo in two separate methods. I'm having trouble getting the description of an image from Flickr and was wondering if you could highlight the error in my script.
for (var i = 0; i < photos.photo.length; i++) {
var descPhoto = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key="+API_KEY+"&photo_id="+photos.photo[i].id+"&format=json&nojsoncallback=1";
var descArr = [];
$.getJSON(descPhoto, function(data) {
var value = data.photo.description._content;
descArr.push(value);
});
link = 'https://farm' + photos.photo[i].farm + '.static.flickr.com/' + photos.photo[i].server + '/' + photos.photo[i].id + '_' + photos.photo[i].secret + '_';
title = this._htmlEscape( photos.photo[i].title );
var lightbox = "lightbox";
listItems +=
'<li ' + 'class="' + liClassNoDots + '">' +
'<a href="' + link + self.options.imageSize + '.jpg" title="' + title + '" class="' + aClassNoDots + '" target="_blank" data-lightbox="' + lightbox + '">' +
<img alt="' + title + '" src="' + link + self.options.thumbnailSize +'.jpg"/>' +
'<div class="hover-box">' +
'<p>' + descArr[i] + '</p>' +
'<button class="box-button view">View larger</button>' +
'<button class="box-button request">Request</button>' +
'</div>';
'</a>' +
'</li>';
}
Getting the title is fine and I've checked by API string calls and they work in the address bar of my browser.
I've used console.log() and the array is printed out correctly and I'm getting the descriptions. However, in each <p> tag the script is returning undefined in each instance.
However, if I run the script through the debugger the parapgraph tags are populated with the descriptions. Can somebody help?!
i think the problem is in following code::
..
$.getJSON(description, function(desc) {
value = desc.photo[ i ].description._content;
});
the service url returns photo object whereas you are using photo array, change to:
..
$.getJSON(description, function(desc) {
value = desc.photo.description._content;
console.log( value );
});

how to display json content in li format in phonegap

i can get the json in the following format
[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
{"data":{"id":"3","user_name":"StudentB","book":"456","role":"Student"}}]
how can i use the data to present like the image below, where the first line is username and second line is book
<button type="button" id="test">Test 123</button>
<ul id="studentList" data-role="listview" data-filter="true"></ul>
var serviceURL = "http://mydomain.com/";
var students;
$("#test").click(function()
{
getStudentList();
});
function getStudentList() {
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
students = data.user_name;
$.each(students, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.user_name + ' ' + student.password + '</h4>' +
'<p>' + student.user_name + '</p>' +
'</li>');
});
$('#studentList').listview('refresh');
});
}
may i ask if the codes above correct?
you are naming response as data..since you response is in array [] you have to loop data first.. get its object which is data again ..
[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
//-^^^^---here
and get the correponding name and password object in the loop...you can get that by . operator.. so inside loop, student.data.user_name gives you username , student.data.book gives you book and similar for others...
try this...
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
//students = data.user_name;
$.each(data, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name +'</h4>' + //here get username
'<p>' + student.data.book + '</p>' + //here get book
'</li>');
});
$('#studentList').listview('refresh');
});
I have done it like that based on your input, you just need to include it into your code. I don't know what you mean by 'second line is book' since there is no book included in your json input + you are trying to access 'student.data.password' which is also not present in input.
Simple version of jsFiddle http://jsfiddle.net/2KMd9/
var json =[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
{"data":{"id":"3","user_name":"StudentB","book":"456","role":"Student"}}];
var students = json;
$.each(students, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name + '</h4>' +
'<p>' + student.data.role + '</p>' +
'</li>');
});
So for your needs:
function getStudentList() {
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
$.each(data, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name + '</h4>' +
'<p>' + student.data.role + '</p>' +
'</li>');
});
$('#studentList').listview('refresh');
});
}

Filter JQuery list with URL

I need to modify some code already in place. There's a block of code that filters a JQuery list using the URL to populate the search input.
E.g.
http://***/store/mobile/page/productList.page?search=football
Automatically enters "football" in the search bar.
Now I'd need to filter the list, without using the search bar.
So lets say my URL would look something like this :
http://***/store/mobile/page/productList.page?football
This would filter the list with football without using the search bar.
Here's the code I need to change. Please tell me if my question is unclear.
$('div[data-url*="productList"]').live("pageshow", function() {
filterValue = getParameterByName("search", location.search);
if (filterValue) {
$('input[data-type="search"]').val(filterValue);
}
refreshList();
});
and:
$.each(catalog.products,
function(index, value) {
if ((!filterValue )
|| value.name.toUpperCase().indexOf(filterValue.toUpperCase()) != -1
|| value.brand.toUpperCase().indexOf(filterValue.toUpperCase()) != -1)
{
items.push('<li id="' + index + '">' +
'<a data-identity="productId" href="./details.page?productId=' + index + '" >' +
'<img class="ui-li-thumb" src="' + value.thumbnail + '"/>' +
'<p>' + value.brand + '</p>' +
'<h3>' + value.name + '</h3>' +
'<span class="ui-li-count">' + value.price + ' $</span></li>') +
'</a>';
}
});
if there will always be only 1 parameter after ? than you could simply get it from page location in javascript, e.g.
var url = document.location;
var params = url.split("?");
filterValue = params[params.length-1]
if (filterValue) {
$('input[data-type="search"]').val(filterValue);
}
refreshList();
example: http://jsfiddle.net/yPgPc/

Categories

Resources