Fix Youtube api data pagination v3 - javascript

I got a so far as good working youtube api data v3 search script but i was so in trouble with this script since days i think im blind it works and paginates everytime 2 entries. But there must be a failure in the js or html code should be easy but i cant figure out please help me. Demo Link is aviable under
Artist search Battle Rap Net Youtube Search
This is the Code so far i used please take a look at the demo link to understand the problem.
The Js Code:
var nextPageToken, prevPageToken;
var firstPage=true;
$(document).ready(function()
{
$('#searchbutton').click(function()
{
// Called automatically when JavaScript client library is loaded.
// alert('i am clicked');
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
// Called automatically when YouTube API interface is loaded .
// Called automatically with the response of the YouTube API request.
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page</button></div>");
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page"+nextPageToken+"</button></div>");
});
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page "+prevPageToken+"</button></div>");
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page "+nextPageToken+"</button></div>");
$('#nextPageButton').click(function()
{
// alert('i am clicked');
console.log(nextPageToken);
searchYouTubeApi(nextPageToken);
});
$('#prevPageButton').click(function()
{
// alert('i am clicked');
console.log(prevPageToken);
searchYouTubeApi(prevPageToken);
});
});
function onYouTubeApiLoad()
{
// See to get a key for your own applications.
gapi.client.setApiKey('MYAPICODE');
searchYouTubeApi();
}
function searchYouTubeApi(PageToken)
{
var searchText= $('#searchtext').val();
//$('#response').append("<div id=\"searching\"><b>Searching for "+searchText+"</b></div>");
$('#response').replaceWith("<div id=\"searching\"><b>Searching for "+searchText+"</b></div>");
// Use the JavaScript client library to create a search.list() API call to Youtube's "Search" resource
var request = gapi.client.youtube.search.list(
{
part: 'snippet',
q:searchText,
maxResults:2,
pageToken:PageToken
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
// $('#response').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page return from request execute method is: "+nextPageToken+"</button></div>");
}
function onSearchResponse(response)
{
var responseString = JSON.stringify(response, '', 2);
var resultCount = response.pageInfo.totalResults;
nextPageToken=response.nextPageToken;
prevPageToken=response.prevPageToken;
// document.getElementById('response').innerHTML += responseString;
//$('#response').append("<div id=count><b>Found "+resultCount+" Results.</b></div>");
$('#count').replaceWith("<div id=count><b>Found "+resultCount+" Results.</b></div>");
//$('#searching').append("<div id=length><b>Length "+response.items.length+" </b></div>");
for (var i=0; i<response.items.length;i++)
{
//store each JSON value in a variable
var publishedAt=response.items[i].snippet.publishedAt;
var channelId=response.items[i].snippet.channelId;
var title=response.items[i].snippet.title;
var description=response.items[i].snippet.description;
var thumbnails_default=response.items[i].snippet.thumbnails.default.url;
var thumbnails_medium=response.items[i].snippet.thumbnails.medium.url;
var thumbnails_high=response.items[i].snippet.thumbnails.high.url;
var channelTitle=response.items[i].snippet.channelTitle;
var liveBroadcastContent=response.items[i].snippet.liveBroadcastContent;
var videoID=response.items[i].id.videoId;
//var firstPage=true;
// console.log(thumbnails_default);
//A HTTP call to this URL with videoID will give all XML info of that video:
//http://gdata.youtube.com/feeds/api/videos?q=videoID
// console.log(videoID);
//replace the first search button with a 'more' button
//$('button').replaceWith("<button type='button' id=More"+i+">More...</button>");
if(firstPage===true)
{
//print the stored variables in a div element
$('#snipp').append("<div id=T><b>Title:</b> "+title+"</div><div id=C><b>Channel ID: </b>"+channelId+"</div><div id=D><b>Description </b>"+description+"</div><div id=P><b>Published on: </b>"+publishedAt+"</div><div id=CT><b>Channel Title: </b>"+channelTitle+"</div><a id=linktoVid href='http://www.youtube.com/watch?v="+videoID+"'><img id=imgTD src=\""+thumbnails_default+"\"/></a><br/><br/><a id=linktoVid1 href='http://www.youtube.com/watch?v="+videoID+"'><video id=vidTD width=\"320\" height=\"240\" controls poster="+thumbnails_default+"><source src='http://www.youtube.com/watch?v="+videoID+">Your browser does not support the video tag.</video></a><br/><br/>");
}
else
{
$('#T').replaceWith("<div id=T><b>Title:</b> "+title+"</div>");
$('#C').replaceWith("<div id=C><b>Channel ID: </b>"+channelId+"</div>");
$('#D').replaceWith("<div id=D><b>Description </b>"+description+"</div>");
$('#P').replaceWith("<div id=P><b>Published on: </b>"+publishedAt+"</div>");
$('#CT').replaceWith("<div id=CT><b>Channel Title: </b>"+channelTitle+"</div>");
$('#linktoVid').replaceWith("<a id=linktoVid href='http://www.youtube.com/watch v="+videoID+"'><img id=imgTD src=\""+thumbnails_default+"\"/></a><br/><br/><a id=linktoVid1 href='http://www.youtube.com/watch?v="+videoID+"'><video id=vidTD width=\"320\" height=\"240\" controls poster="+thumbnails_default+"><source src='http://www.youtube.com/watch?v="+videoID+">Your browser does not support the video tag.</video></a><br/><br/>");
}
// $('#snipp').append("<div id=C"+i+">Channle ID: "+channelId+"</div><br/>");
//link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=76TlUlPZQfQ&feature=youtube_gdata'/>
}
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\" onclick=\"alert('Hello world!')\">Next Page "+nextPageToken+"</button></div>");
// return nextPageToken;
firstPage=false;
}
The HTML:
<body>
<div id="search">
<input type="text" value="eureka" id="searchtext"><button type="button" id="searchbutton">Find</button>
</div>
<button type="button">Search Me...</button>
<pre id="response">
</pre>
<pre id="count"></pre>
<pre class="vID"></pre>
<div id="snipp">
<div id=T0
</div>
<br/><br/><br/>
</body>

After create a jsfiddle with your code, I could check the pagination is working correctly.
The problem you're facing lies in your HTML code (most specific: in how you're building your HTML code).
My humble advice is that "instead of using append", re-creates the HTML that renders the current page.
Also, just after all controls loaded in the screen, the "prevPageButton" and "nextPageButton" buttons shows undefined.
For this situation, change these lines:
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page " + prevPageToken + "</button></div>");
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page " + nextPageToken + "</button></div>");
For this:
if (prevPageToken == undefined) {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page</button></div>");
} else {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page " + prevPageToken + "</button></div>");
}
if (nextPageToken == undefined) {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page</button></div>");
} else {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page " + nextPageToken + "</button></div>");
}
After a few modifications, you can check here the updated and working jsfiddle.
The tl;dr version is as follows:
Logic for build the HTML code was replaced for set a variable that (in the for-loop) builds the HTML code.
At the end of the loop, the HTML is added directly to the div container called "snipp".
Removed other HTML unneccesary code.
This is the modified code:
HTML:
<div id="search">
<input type="text" value="eureka" id="searchtext"><button type="button" id="searchbutton">Find</button>
</div>
<button type="button">Search Me...</button>
<pre id="response">
</pre>
<pre id="count"></pre>
<pre class="vID"></pre>
<div id="snipp"></div>
JS:
function onSearchResponse(response) {
var responseString = JSON.stringify(response, '', 2);
var resultCount = response.pageInfo.totalResults;
nextPageToken = response.nextPageToken;
prevPageToken = response.prevPageToken;
$('#count').replaceWith("<div id=count><b>Found " + resultCount + " Results.</b></div>");
// This variable will save the HTML code in construction.
var HTML_CONTENT = "";
for (var i = 0; i < response.items.length; i++) {
//store each JSON value in a variable
var publishedAt = response.items[i].snippet.publishedAt;
var channelId = response.items[i].snippet.channelId;
var title = response.items[i].snippet.title;
var description = response.items[i].snippet.description;
var thumbnails_default = response.items[i].snippet.thumbnails.default.url;
var thumbnails_medium = response.items[i].snippet.thumbnails.medium.url;
var thumbnails_high = response.items[i].snippet.thumbnails.high.url;
var channelTitle = response.items[i].snippet.channelTitle;
var liveBroadcastContent = response.items[i].snippet.liveBroadcastContent;
var videoID = response.items[i].id.videoId;
// Buld the HTML to render at the current page.
HTML_CONTENT += "<div id='video_item'> " +
" <div id=T><b>Title:</b>" + title + "</div> " +
" <div id=C><b>Channel ID: </b>" + channelId + "</div> " +
" <div id=D><b>Description </b>" + description + "</div> " +
" <div id=P><b>Published on: </b>" + publishedAt + "</div> " +
" <div id=CT><b>Channel Title: </b>" + channelTitle + "</div> " +
" <a id='linktoVid' href='http://www.youtube.com/watch?v=" + videoID + "'><img id='imgTD' src='" + thumbnails_default + "' /></a><br/><br/><a id='linktoVid1' href='http://www.youtube.com/watch?v=" + videoID + "'><video id='vidTD' width=\"320\" height=\"240\" controls poster='" + thumbnails_default + "'><source src='http://www.youtube.com/watch?v=" + videoID + "'>Your browser does not support the video tag.</video></a><br/><br/> " +
"</div>";
}
// Post all HTML generated code (built in the previous for-loop).
document.getElementById('snipp').innerHTML = HTML_CONTENT;
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\" onclick=\"alert('Hello world!')\">Next Page "+nextPageToken+"</button></div>");
// return nextPageToken;
firstPage = false;
}

Related

Javascript - InnerHTML doesn't edit the DOM

I'm working on a project with Laravel. Now I'm coding the feature which prints all activities responsible. Before I was using foreach loop in PHP to print all of my activities (from the DB).
But now I have to use JS to print these activities because I want to add a filter (and avoid page to reload).
I have created this script in my view :
<script>
containerE = document.getElementById("container");
var request = new XMLHttpRequest();
request.open("GET","{{route('APIManifs')}}", false);
request.send(null);
responses = JSON.parse(request.responseText);
function expandResults(value){
for (var i in responses){
if (responses[i].status === value) {
containerE.innerHTML = containerE.innerHTML +
"<div class=\'col-md-5 offset-1\' id=\'1\'>" +
"<div class=\'card\'>" +
"<a href='/manif/" + responses[i].id + "'"+" ><div class=\'card-header\' style=\'text-align: center\'>"+
"<img src='"+responses[i].image+"'><br>"+
responses[i].name+" | "+responses[i].date_add+"<br>"+
"</div> </a>"+
"<div class=\'card-body\'>"+
"Nom : "+responses[i].name+"<br>"+
"Description : "+responses[i].description+"<br>"+
"</div>"+
"</div>"+
"</div>";
containerE.innerHTML = containerE.innerHTML + "Arg";
console.log(responses[i].status+"=="+value);
}
else{
console.log(responses[i].status+"<>"+value);
}
}
}
</script>
I got the information but impossible to print my HTML in the DOM! When I copy paste the inner HTML code in the console it's work.
Do you have any ideas on how to accomplish this?
Thank's in advance!

How to execute JAVA code from JS in JSP

I'm working with Java Web at Netbeans 8.1, actually I'm working with AJAX in the proyect and this issue stops me:
This is my JS function in JSP:
$("#formAddFundo").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr('action');
var status = 0;
if (document.getElementById("chkFundo").checked)
var status = 1;
/* Send the data using post with element id name and name2*/
var posting = $.post(url, {
hIdFundo: $('#hIdFundo').val(),
txtNombre: $('#txtNombre').val(),
status: status,
btnAddGrid: $('#btnAddGrid').val()
});
/* Alerts the results */
posting.done(function(data) {
$.get('addFundo', function(responseJson) {
var t = $('#dt_basic').DataTable();
t.clear();
$.each(responseJson, function(index, objeto) { // Iterate over the JSON array.
var estado;
if (objeto.status === 1) {
estado = "Activo";
} else {
estado = "No activo";
}
t.row.add([
objeto.idfundo,
objeto.nombre,
estado,
"<i class=\"btn btn-secondary fa fa-pencil\" onclick=\"update('" + objeto.nombre + "', '" + objeto.idfundo + "', '" + objeto.status + "');\"></i></a><a><i class=\"btn btn-secondary fa fa-trash-o\" onclick=\"borrar('" + objeto.nombre + "', '" + objeto.idfundo + "');\"></i></a>"
]).draw(false);
});
$('#alerta').html("<div class='alert alert-warning'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Atención!</strong> " + <%= session.getAttribute("Respuesta") %> +" </strong></div>");
});
limpiar();
});
});
This is my servlet where JS goes to get response:
String json = new Gson().toJson(listaFundos);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
request.getSession().setAttribute("Respuesta", resp);
Now. I need to print a HTML at (#alerta) in JSP without page refresh when POST method ends his function with Json. Session variables and scripplets only executes once at page refresh, not for further executions..
$('#alerta').html("<div class='alert alert-warning'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Atención!</strong> " + <%= session.getAttribute("Respuesta") %> +" </strong></div>");

Avoid duplicated function call in jquery?

I have build a function getuser() in which I recieve json data from php into javascript. I call this function when document gets ready. My problem is that I am also using jquery post for live updation of that record and for that reason I have to call that function getuser() again due to this it shows duplicate result. First when document gets ready socend on jquery post function.
HTML
<!--It has onclick event-->
<button type="submit" class="btn btn-primary modify" onclick="update_user()">UPDATE</button>
JQUERY
//This is function which gets json array from php
function getuser() {
$.get("getuser.php", function (data) {
var data = JSON.parse(data);
for (var i = 0, len = data.length; i < len; ++i) {
var student = data[i];
var slash = " / ";
$("#output").append("<tr><td>" + student.name + "</td><td>" + student.gender + "</td><td>" + student.age + "</td>" +
"<td>" + student.city + "</td><td><a href='#' style='text-decoration: none' class='update' id='" + student.id + "' onclick='reply_click(this.id)'>Update</a>" + slash + "<a style='text-decoration: none' href='#'>Delete</a></td></tr>");
}
});
}
//when document gets ready it will show the record
if($(document).ready()) {
// getuser();
getuser();
}
//This is jquery post. When I click button (in html section) it will get form values and sent to php page
//in return it will call getuser() function again which results of duplicate display of record
$(document).ready(function(){
$('.modify').click(function() {
var gender = '';
if($('.male').is(':checked')){
gender='Male';
}else{
gender='Female';
}
$.post("update.php",
{name: $('.name').val(),gender:gender,city:$('.city').val(),age:$('.age').val(),id:$('.id').val()},
function (data) {
//here is the function call again
getuser();
}
);
});
});
Kindy tell me that is there any way I avoid second call in post function and the record gets update without function call again.I need to avoid duplicate result. Thanks in advance!
First off, you need to read the docs on jquery document ready, and learn the difference between a function reference and actually calling a function. document.ready expects you to pass in a function definition to be called when the page is ready. It doesn't actively tell you if the page is ready, the first way you're calling it. The second way you're calling it is actually correct.
Second, replace $("#output").append with $("#output").html, which will update/replace the contents of that element every time, instead of just adding more and more.
Your if test will always return true because document.ready returns the JQuery object. So, you are always causing the call to getuser() to happen.
You can see the return value from document.ready() here:
console.log($(document).ready());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is an incorrect usage of document.ready(). You don't need to write a test for document.ready, just write a callback function for that event and let the browser do it correctly for you.
Read the docs on document.ready()
Solution:
This:
//when document gets ready it will show the record
if($(document).ready()) {
// getuser();
getuser();
}
Should be this:
//when document gets ready it will show the record
$( document ).ready(getuser);
Or even:
$(getuser);
As for you getting the results a second time, just overwrite the old results instead of appending them.
This: $("#output").append(...
Should be: $("#output").html(...
All of you thanks for your suggestions. I have found the solution here by just adding $("#tbody").html(''); in getuser() before loop. Here is the code which works fine for me
function getuser() {
$.get("getuser.php", function (data) {
var data = JSON.parse(data);
$("#tbody").html('');//newly added
for (var i = 0, len = data.length; i < len; ++i) {
var student = data[i];
var slash = " / ";
$("#output").append("<tr><td>" + student.name + "</td><td>" + student.gender + "</td><td>" + student.age + "</td>" +
"<td>" + student.city + "</td><td><a href='#' style='text-decoration: none' class='update' id='" + student.id + "' onclick='reply_click(this.id)'>Update</a>" + slash + "<a style='text-decoration: none' href='#'>Delete</a></td></tr>");
}
});
}
All of you thanks again!

How to get more JSON data on scroll or while scrolling?

I have the following code below which returns some results when the user searches a term.
Once i get some results,I want to add feature which will allow me to get more data when scrolling down ward?
NOTE: I dont want to use any plugin(s).
$(document).ready(function() {
$("#submit").click(function (event) { // wire up this as an onclick event to the submit button.
var searchTerm = $("#search").val(); // get the user-entered search term
var URL = "http://api.flickr.com/services/feeds/photos_public.gne";
//var URL = "http://api.flickr.com/services/feeds/photos_public.gne";
var ID = "25053835#N03";
//var MYID-"84215563#N08";
//var tagmode="&tagmode=any";
//var format ="&format=json";
var tags="&tags="+ searchTerm;
var tagmode="&tagmode=any";
var jsonFormat = "&format=json&jsoncallback=?";
var ajaxURL= URL+"?jsoncallback=?id="+ID+tags+tagmode+jsonFormat;
//var ajaxURL= URL+"?"+tags+tagmode+jsonFormat;
$.getJSON(ajaxURL,function(data){
//$("h1").text(data.title);
//alert(data.length);
var photoHTML;
$("#photos").empty();
if (data.items.length) {
alert(data.items.length);
$.each(data.items, function(i,photo) {
//var photoHTML = "<h4>" +photo.tags + "</h4>";
photoHTML = "<p>";
photoHTML += '<a href="' + photo.link + '">';
photoHTML += '<img src="' + photo.media.m + '" alt="' + photo.media.m + '" title="' + photo.media.m + '"></a>';
photoHTML = "</p>";
$('#photos').append(photoHTML).fadeIn(200);
});
} else {
alert(data.items.length);
photoHTML = "<h2> No Results</h2>";
$('#photos').append(photoHTML).fadeIn(200);
}
//$('#photos').append(photoHTML).fadeIn(200);
});
});
});
You could use the jquery .scroll() method. You have two options, save all data when page loads then display as user scrolls OR make ajax request every time there is a scroll down request.
$("#yourSelector").on('scroll', function(){
// do stuff
});
or simply using the shortcut:
$("#yourSelector").scroll(function(){
// do stuff
});
I hope this helps!
Here is a link to jquery scroll api to know about the options (such as specifying scroll DOWN): http://api.jquery.com/scroll/
You can also bind scroll event using jquery:
Put your whole code into a function:
function myfun(){
//-- you code
}
and call myfun() from both event:
on click event-
$("#submit").click(function (event) {
myfun();
});
on scroll event -
$("#yourSelector").scroll(function(){
myfun();
});

Trying to pull location info on first connection in linkedin with javascript api

I have working code for pulling my connections info from Linkedin.
However, whenever I try to pull location I get strange results.
This code works but you will see 'object OBJECT' where location is supposed to be.
<html lang="en">
<head>
<title>LinkedIn Industries</title>
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: xxxxxxx
onLoad: onLinkedInLoad
scope: r_network,r_emailaddress,r_fullprofile,r_basicprofile,r_contactinfo
</script>
</head>
<body>
<p>This example demonstrates how to retrieve a user's connections. It also uses the LinkedIn auth events (load, login, logout) to control behavior.</p>
<!-- NOTE: be sure to set onLoad: onLinkedInLoad -->
<script type="text/javascript">
function onLinkedInLoad() {
IN.Event.on(IN, "auth", function() {onLinkedInLogin();});
IN.Event.on(IN, "logout", function() {onLinkedInLogout();});
}
function onLinkedInLogout() {
setConnections({}, {total:0});
}
function onLinkedInLogin() {
// here, we pass the fields as individual string parameters
IN.API.Connections("me")
.fields("id", "firstName", "lastName", "pictureUrl", "publicProfileUrl","location:(name)")
.result(function(result, metadata) {
setConnections(result.values, metadata);
});
}
function setConnections(connections) {
var connHTML = "<ul>";
for (id in connections) {
connHTML = connHTML + "<li><a href=\"" + connections[id].publicProfileURL + "\">";
/* picture url not always there, must be defensive */
if (connections[id].hasOwnProperty('pictureUrl')) {
connHTML = connHTML + "<img align=\"baseline\" src=\"" + connections[id].pictureUrl + "\"></a>";
} else {
connHTML = connHTML + "<img align=\"baseline\" src=\"http://static02.linkedin.com/scds/common/u/img/icon/icon_no_photo_80x80.png\"></a>";
}
connHTML = connHTML + " <a href=\"" + connections[id].publicProfileUrl + "\">";
connHTML = connHTML + connections[id].firstName + " " + connections[id].lastName + "</a>";
connHTML = connHTML + " (Location: " + connections[id].location + ")</li>";
}
connHTML = connHTML + "</ul>";
document.getElementById("connectionsdata").innerHTML = connHTML;
}
</script>
<script type="IN/Login">
<div id="connectionstest">
<p>Current User's Connections:</p>
<div id="connectionsdata"></div>
</div>
</script>
</body>
</html>
The main issue really exists in location, in the documentaion this should be replaced with location.name, however, whenever I do this I get nothing back, although I can see that there is a XHR response with a json, which has:
location:{"name":"Dublin etc"}
Please help solve the mystery of the hidden location
EDIT: 5/23/2013-
In Chrome's Developer tools I can see a message saying (Uncaught TypeError: Cannot read propertry 'name' of undefined - hopes this help someone help me
When I look in the console of the chrome developer, there is more detail on the above uncaught type error: Uncaught TypeError: Cannot read property 'name' of undefined linkedconnect.html:55
setConnections linkedconnect.html:55
(anonymous function) linkedconnect.html:36
Sslac.Class.Constructor.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.b framework:3242
(anonymous function) framework:173
Sslac.Class.Constructor.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.storedFailureResults
framework:3247
(anonymous function) framework:173
g framework:3135
pub.incoming framework:801
_window_onMessage framework:566
Maybe you can temporary replace the code setting html with a log of what the connections array really contains:
//connHTML = connHTML + " <a href=\"" + connections[id].publicProfileUrl + "\">";
//connHTML = connHTML + connections[id].firstName + " " + connections[id].lastName + "</a>";
//connHTML = connHTML + " (Location: " + connections[id].location + ")</li>";
console.log(connections[id]);
When you log an object you can click on it to inspect it's properties, maybe some of the items simply do not contain a location. In that case you can try:
function setConnections(connections) {
var connHTML = "<ul>",
tmpLocation;
.....
tmpLocation= (connections[id].location && connections[id].location.name)
?connections[id].location.name:"Unknown";
connHTML = connHTML + " (Location: " + tmpLocation + ")</li>";
As the error message is suggesting you are displaying an object when you are actually trying to display a string. Therefore you need to to pick the correct property of that object:
connHTML = connHTML + " (Location: " + connections[id].location.name + ")</li>";

Categories