Loop stopping when undefined - json

UPDATE 6:
Based on the console.log, I have noticed that some of the objects have:
thumbnail: Array[2]
Others have:
thumbnail: Object
and others don't have it at all.
So it seems that what #Felix Kling could be true.
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20%22http%3A%2F%2Ffeeds.bbci.co.uk%2Fnews%2Frss.xml%22&format=json&callback=cbfunc
if you can't access the link, try:
http://pastebin.com/T4GPQvtk
UPDATE 5:
I am still getting url as undefined with:
for (var i = 0; i < news.length; i++) {
news[i].thumbnail = ( $.isArray( news[i].thumbnail ) ) ? news[i].thumbnail : [news[i].thumbnail];
buildHTML.push( "<a href='" + news[i].thumbnail[0].url + "' target='_blank'>" + news[i].title + "</a><br />" + news[i].pubDate );
}
UPDATE 4:
The following:
buildHTML.push( "<a href='" + news[i].thumbnail[0] ? news[i].thumbnail[0].url : $.isArray( news[i].thumbnail ) + "' target='_blank'>" + news[i].title + "</a><br />" + news[i].pubDate );
gives me:
Uncaught TypeError: Cannot read property 'url' of undefined
UPDATE 3:
The following does not seem to work either:
buildHTML.push( "<a href='" + news[i].thumbnail[0] ? news[i].thumbnail[0].url : news[i].thumbnail.url + "' target='_blank'>" + news[i].title + "</a><br />" + news[i].pubDate );
The error I get is:
Uncaught TypeError: Cannot read property 'url' of undefined
UPDATE 2:
The following does not seem to work:
buildHTML.push( "<a href='" + news[i].thumbnail=$.isArray(news[i].thumbnail)?news[i].thumbnail:[news[i].thumbnail] + "' target='_blank'>" + news[i].title + "</a><br />" + news[i].pubDate );
The error I get is:
Uncaught ReferenceError: Invalid left-hand side in assignment
$.ajax.successyql_news_widget.js:25
bjquery-1.4.2.min.js:124
c.extend.ajax.Ajquery-1.4.2.min.js:125
(anonymous function)yql:1
UPDATE 1:
The problem happens, when I add the image to push as follows:
buildHTML.push( "<img src='" + news[i].thumbnail[0].url + "' /><a href='" + news[i].link + "' target='_blank'>" + news[i].title + "</a><br />" + news[i].pubDate );
ORIGINAL QUESTION:
From the following url:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20%22http%3A%2F%2Ffeeds.bbci.co.uk%2Fnews%2Frss.xml%22&format=json&callback=cbfunc
I am trying to capture the data via a look like this:
function get_news() {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20%22http%3A%2F%2Ffeeds.bbci.co.uk%2Fnews%2Frss.xml%22&format=json&callback=cbfunc&rand=" + Math.random(),
type: 'GET',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'cbfunc',
error: function(xhr, status, error) {
alert(xhr.responseText);
},
success: function(data) {
var buildHTML = [];
var news = data.query.results.rss.channel.item;
for (var i = 0; i < news.length; i++) {
buildHTML.push( "<a href='" + news[i].link + "' target='_blank'>" + news[i].title + "</a><br />" + news[i].pubDate );
}
$('.portlet-content').empty().append(buildHTML.join("<br /><br />"))
}
});
}
This works fine as long as the thumbnail section looks like this:
"thumbnail": [
{
"height": "49",
"url": "http://news.bbcimg.co.uk/media/images/48915000/jpg/_48915868_48915872.jpg",
"width": "66"
}
{
"height": "81",
"url": "http://news.bbcimg.co.uk/media/images/52468000/jpg/_52468689_48915872.jpg",
"width": "144"
}
]
However, when the thumbnail section looks like this:
"thumbnail": {
"height": "81",
"url": "http://news.bbcimg.co.uk/media/images/53705000/jpg/_53705922_012314461-1.jpg",
"width": "144"
}
I get an error "undefined", the loop stops and I get nothing on the screen.
How do I ignore those, and continue the script without it stopping on the error?

You may create an array if the json matches the 2nd example(isn't an array yet):
news[i].thumbnail=($.isArray(news[i].thumbnail))
? news[i].thumbnail
: [news[i].thumbnail];

Based on your comments, you seem to want this:
for (var i = 0; i < news.length; i++) {
var item = news[i];
if($.isArray(item.thumbnail)) {
var size = +item.thumbnail[0].width * +item.thumbnail[0].height,
selected = 0;
for(var j = 1, jl = item.thumbnail.length; j < jl; j++) {
var t_size = +item.thumbnail[j].width * +item.thumbnail[j].height;
if(t_size < size) {
size = t_size;
selected = j;
}
}
buildHMTL.push("<img src='" + news[i].thumbnail[selected].url + "' />");
}
buildHTML.push( "<a href='" + item.link + "' target='_blank'>" + item.title + "</a><br />" + item.pubDate );
}

Add [] brackets to cast "thumbnail" from object to array.
"thumbnail": [ {
"height": "81",
"url": "http://news.bbcimg.co.uk/media/images/53705000/jpg/_53705922_012314461-1.jpg",
"width": "144"
}]
will work

You can use a Try catch or a simple IF before the code to check to see if the code is in the format you want before attempting to manipulate it. The issue seems to be that if your thumbnails 'array' is only one object its not sent as an array. A simple if check could stop this issue your having.
you can use a conditional operator which would go something like this:
buildHTML.push( "<img src='" + news[i].thumbnail[0] ? news[i].thumbnail[0].url : news[i].thumbnail.url + "' /><a href='" + news[i].link + "' target='_blank'>" + news[i].title + "</a><br />" + news[i].pubDate );
UPDATE
this conditional expression will find the URL or it will just return "". I didn't see that some items have no URL which is why my first suggestion didn't work. Use this expression for getting your url
news[i].thumbnail ? news[i].thumbnail[0] ? news[i].thumbnail[0].url : news[i].thumbnail.url : ''

Related

Looping through AJAX result and post to HTML,

I have the following AJAX code for processing a returned results from the database,
$.ajax({
type: 'POST',
async: true,
url: "../../../avocado/private/functions/measures.php",
data: {name:selectedValue},
success: function(data, status){
var selectedData = JSON.parse(data);
console.log(selectedData);
document.getElementById("measures").innerHTML = "<div id=\"measures\">"
+ "<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[0][6]+"</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[0][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[0][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[0][9]+"</td></tr>"
+ "</table>"
+ "</div>";
},
error: function(xhr, status, err) {
alert(status + ": " + err);
}
});
The data returned is a 2D array, like this below,
Array[5]
0: Array[14]
1: Array[14]
2: Array[14]
3: Array[14]
4: Array[14]
so what I want to do is to loop each array and display the inner information on the HTML page but I have no idea how I should go about doing it.. this code only returns the values stored on index[0].
Can I please get some help?
==============================================================================
UPDATED
So I tried to use Jquery.append() like the following below..
jQuery.each( selectedData, function( i, val ) {
$("measures").append(
"<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[i][6]+"</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[i][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[i][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[i][9]+"</td></tr>"
+ "</table>"
);
});
/*
document.getElementById("measures").innerHTML = "<div id=\"measures\">"
+ "<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[0][6]+"</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[0][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[0][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[0][9]+"</td></tr>"
+ "</table>"
+ "</div>";
*/
now..its not appending any values to the div #measures at all...
I have not tried the code. But I hope this will help you.
document.getElementById("measures").innerHTML = "<div id=\"measures\">";
$.each( selectedData, function( index, value ){
$.each( index, function( index2, value2 ){
$('#measures').append(value2);
});
});

How do I make a JSON object produce HTML on the page

Here is my JSON
var gal = [
{
"folder":"nu_images",
"pic":"gd_42.jpg",
"boxclass":"pirobox_gall",
"alt":"Rand Poster 1",
"title":"Rand Poster 1",
"thfolder":"th",
"thumbpic":"th_gd_42.jpg"
},
{
"folder":"nu_images",
"pic":"gd_13.jpg",
"boxclass":"pirobox_gall",
"alt":"Explosive Pixel Design",
"title":"Explosive Pixel Design",
"thfolder":"th",
"thumbpic":"th_gd_13.jpg"
}
];
and here is my for loop
for (i = 0; i < gal.length; i++) {
document.getElementById("gallery").innerHTML = "" + "<img src=\"" + "http:\/\/galnova.com\/" + gal[i].folder + "\/" + "th\/" + gal[i].thumbpic + "\"" + "border=\"0\"" + "alt=\"" + gal[i].alt + "\"" + "title=\"" + gal[i].title + "\"\/>" + ""
};
I am trying to make my JSON show all of the objects in HTML one after the other. I can get it to show the first one or whatever number I put into the array but I don't know how to make it generate a list of them.
Here is a link to my jsfiddle. Any help you can offer would be greatly appreciated.
http://jsfiddle.net/o7cuxyhb/10/
It's being generated here <p id="gallery"></p> just not correctly.
You're overwriting your html with every loop iteration:
document.getElementById("gallery").innerHTML = ...
^---
Perhaps you want something more like
document.getElementById("gallery").innerHTML += ...
^---
which will concatenation the original html contents with your new stuff.
And technically, you shouldn't be doing this in a loop. Changing .innerHTML like that causes the document to be reflowed/re-rendered each time you change .innerHTML, which gets very expensive when you do it in a loop. You should be building your html as a plain string, THEN adding it to the dom.
e.g.
var str = '';
foreach(...) {
str += 'new html here';
}
document.getElementById("gallery").innerHTML += str;
for (i = 0; i < gal.length; i++) {
document.getElementById("gallery").innerHTML += "" + "<img src=\"" + "http:\/\/galnova.com\/" + gal[i].folder + "\/" + "th\/" + gal[i].thumbpic + "\"" + "border=\"0\"" + "alt=\"" + gal[i].alt + "\"" + "title=\"" + gal[i].title + "\"\/>" + "" };
Add a += instead of an = after innerHTML
Try this:
function displayJson(jsonArray){
var container = document.getElementById("gallery");
for (var i=0; i<jsonArray.length; i++){
var newElement = document.createElement("a").innerHTML = jsonToHtml(jsonArray[i])
container.appendChild(newElement);
}
}
function jsonToHtml(jsonObj){
//Define your dom object here
var el = document.createElement("a").innerHTML = '' // you code here
...
return el;
}
displayJson(gal);

SQLite to JSON in a simple JS function - parsing JSON

I want to transform a SQLite Database into a JSON object. After searching the web I decided to write a function by myself. I'm still a beginner in JS/JSON/jQuery and I thought the following code should work:
function sqlite2json(){
newJson = '{ "$resources": [';
offlinedb = openDatabase (shortName, version, displayName, maxSize);
offlinedb.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM Zaehlliste;', [],
function(transaction, result) {
if (result != null && result.rows != null) {
for (var k = 0; k < result.rows.length; k++) {
var row = result.rows.item(k);
newJson += '{ "Field0":"' + row.Field0 + '", "Field1":"' + row.Field1 + '", "Field2":"' + row.Field2 + '", "Field3":"' + row.Field3 + '", "Field4":"' + row.Field4 + '", "Field5":"' + row.Field5 + '"},'
}
jsonall = newJson + ']}';
alert(jsonall); //shows me a correct JSON as string
jsonobjoff = $.parseJSON(jsonall);
for (i = 0; i < jsonobjoff.$resources.length; i++) {
$('#json').append("<li>" + jsonobjoff.$resources[i].Field0 + " " + jsonobjoff.$resources[i].Field1 + " " + jsonobjoff.$resources[i].Field2 + " " + jsonobjoff.$resources[i].Field3 + " " + jsonobjoff.$resources[i].Field4 + " " + jsonobjoff.$resources[i].Field5 + "</li>");
}
}
},errorHandler);
},errorHandler, nullHandler);
}
This second for-loop and putting content into that element with its id="json" is just to control, that I finally got a true JSON object, but unfortunately there is no list appearing. The alert after declaring jsonall shows me a correct JSON-Object as a string. I think that parseJSON is not working, but I have no clue, why it is not working. Could it be that comma after the last entry of the JSON-Object? I know this is not clean, but it should still work...?
the json you generate is incorrect.
you add a trailing comma after every object (in your first for loop), but the last entry shouldn't add a comma, or it isnt valid json.
change this:
newJson += '{ "Field0":"' + row.Field0 + '", "Field1":"' + row.Field1 + '", "Field2":"' + row.Field2 + '", "Field3":"' + row.Field3 + '", "Field4":"' + row.Field4 + '", "Field5":"' + row.Field5 + '"},';
to:
if(k > 0) newJson += ',';
newJson += '{ "Field0":"' + row.Field0 + '", "Field1":"' + row.Field1 + '", "Field2":"' + row.Field2 + '", "Field3":"' + row.Field3 + '", "Field4":"' + row.Field4 + '", "Field5":"' + row.Field5 + '"}';
that will work (if you dont have special characters in your strings)
i would recommend that you use this json encoder instead of manually generating the string, it will handle special characters too, which yours will have problems with: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
code for this:
change newJson = '{ "$resources": ['; to newJson = { $resources: [] };
and in the loop:
newJson.$resources[k] = { Field0: row.Field0, Field1: row.Field1, Field2: row.Field2, Field3: row.Field3, Field4: row.Field4, Field5: row.Field5 };
you could just use newJson.$resources[k] = row; here, but if row has more Fields that you dont want to show, they will be taken too
create the json string:
jsonall = JSON.stringify(newJson);

Converting html to Json object

I'm currently working on a project where I need to convert some older code into a json object. We're taking the result set from a sql query and returning the categories it gives back as json. I'm not that well versed in javascript let alone json so I'm not sure what's the simplest way to go about this. Here is the function I need to change into JSON:
function createOutputCategories(){
try
{
output =
"<html>" +
"<head>" +
"<title>" +
"You can find it!" +
"</title>" +
"</head>" +
"<body bgcolor='#CED3F3'>" +
"<a href='" + url + "file.xsjs?parent=1'>" +
"</a>" +
"<br><br>";
if(parent === "1"){
output = output + "<h3><font color='#AAAAAA'>Home</font>";
}else{
output = output +"<a href='javascript:history.back()'>" +
"<h3>Back";
}
output = output +
"</h3>" +
"</a>" +
"<h1>" +
"Categories:" +
"</h1>";
while(rs.next()){
if(rs.getString(3) === 0 || rs.getString(3) === null || rs.getString(3) === undefined || rs.getString(3) === "0" ){
output = output + "<br><a href='" + url + "yeti.xsjs?parent=" + rs.getString(1) + "'>" + rs.getString(2) + "</a>";
}else{
output = output + "<br><a href='" + url + "yeti.xsjs?parent=" + rs.getString(1) + "'>" + rs.getString(3) + "</a>";
}
}
}catch(Exception){
$.response.contentType = "text/plain";
$.response.setBody( "Failed to retreive data" );
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
Here is what I have so far but I am not returning a valid JSON object:
function createOutputCategories(){
try{
output =
"category: {name = \"" + parent + "\"; description = \"\"}";
output = output +
"subcategories: [ ";
while(rs.next()){
output = output +
"{ catid = \"" + rs.getString(1) + "\"; catname = \"" + rs.getString(2) + "\"; altname = \"" + rs.getString(3) + "\"; description = \"" + rs.getString(4) + "\"}";
}
output = output +
"];";
}
catch(Exception){
$.response.contentType = "text/plain";
$.response.setBody( "Failed to retreive data" );
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
If I need to provide anything else please let me know! Thanks!
Do you want to output a javascript object to a string?
Construct the object:
var category=new Object();
category.name="Name";
category.description="My lovely description";
category.subcategories=[];
var subCat=new Object();
subCat.catid=1;
subCat.catname="My subcat";
category.subcategories.push(subCat);
Alternatively, you could construct the object using literals:
var category={
name:"Name",
description:"My lovely description",
subcategories:[
{catid:1,catname:"My subcat"}
]
};
Then return the object as string.
return JSON.stringify(category);
A reference to Javascript objects if you need more help:
http://www.w3schools.com/js/js_objects.asp

Graph API - FB - Getting crazy already. :s - Getting profile pictures

I can get the profile pictures from this:
data": [
{
"id": "11111111111_22222222222",
"from": {
"name": "Some Name",
"category": "Non-profit organization",
"id": "11222131212211"
},
I'm doing like so:
$.each(json.data,function(i,fb){
html += "<img id=\"image"+i+"\" src=\"http://graph.facebook.com/" + fb.from.id + "/picture\"/>";
}
No problems.
However, later on the graph I have:
"id": "11111111111_2222222222",
"to": {
"data": [
{
"name": "Some Name",
"category": "Non-profit organization",
"id": "11222131212211"
And I need to grab this id but I've tried:
alert(fb.to.data.id); got nothing.
If I do: alert(fb.to) I got "undefined".
Has anyone had this sort of problems or similar. As you may notice I'm not at all versatle onto programing matters, however, I will do my best to solve this issue.
1) How can I display the profile image on the second case?
2) How can I say: use the fb.from.id only when the graph has that.
About 2), please note that if I comment the line:
//html += "<img id=\"image"+i+"\" src=\"http://graph.facebook.com/" + fb.from.id + "/picture\"/>";
no images will be show and all post information (except the profile picture) is displayed on the viewport.
If I deal only with the first part of this graph (the one with "from:") I get the picture for that post.
SO, the issue must be, indeed, on the second graph part. The one with the "to:" that I can't grab the ID.
I've tried, as well, to avoid rendering the image on the second case but, at least run the first one. No luck at all.
if (fb.from.id != undefined) {
//do something;
}
The second part of the graph still returns an error.
With all this mess, that I can re-arrange, can I please ask your help. :S
**
Update:
**
The js code:
function fbFetch(){
var url = "https://graph.facebook.com/125120007543580/feed&callback=?&limit=2";
var i = 0;
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url,function(json){
var html = "<div id=\"faceWall\">";
//loop through and within data array's retrieve the message variable.
$.each(json.data,function(i,fb){
var idTotal = fb.id;
var ids = idTotal.split("_");
var href = "http://www.facebook.com/"+ids[0]+"/posts/"+ids[1];
var msg = fb.message;
//adicionado
if (msg == undefined) {
msg = 'Cick here to see the post title';
} else if (msg.length > 150) {
msg = msg.substr(0,200)+"...";
}
//ISSUE HERE. IF I COMMENT THIS LINE ALL GOES WELL BUT NO PROFILE PICTURES ARE DISPLAYED.
html += "<img id=\"imagem"+i+"\" src=\"http://graph.facebook.com/" + fb.from.id + "/picture\"/>";
html += "<div id=\"textoFaceWall\">";
html += "<p id=\"msg"+i+"\">";
//adicionado fb.name em vez de fb.from.name:
if (fb.name == undefined) {
html += "" + fb.from.name + " - " + msg + "</p>";
} else {
html += "" + fb.name + " - " + msg + "</p>";
}
html += "<p class=\"dataPostWall\" id=\"data"+i+"\">"+ dataFinal + "</p> ";
html += "</p>";
html += "</div>";
html += "<img class=\"linhaHomePageCanais\" src=\""+baseUrl+"/lib/img/linhaWall.png\" alt=\"linha wall\"/>";
});
html += "</div>";
$("#coluna2").append(html);
});
};
fbFetch();
And part of the graph:
({
"data": [
{
"id": "125120007543580_150880001634837",
"from": {
"name": "Some Name",
"category": "Non-profit organization",
"id": "125120007543580"
},
{
"id": "125120007543580_111122368963254",
"to": {
"data": [
{
"name": "Some Name",
"category": "Non-profit organization",
"id": "125120007543580"
}
]
},
I need to display the profile from fb.to.data.id,
I now notice, however, that data has [ instead of {, and that could mean that, in order to access id, I need to use another syntax perhaps?
Since the to parameters can holds more that one user, it's an array of objects. So you need to loop over that too:
if(fb.to) {
$.each(fb.to.data, function(j,to_user) {
// now you access it to_user.id
});
}
If you only want to show the first profile picture then use fb.to.data[0].id.
EDIT:
Okay, based on your comments and updated, here is your code with a working approach:
function fbFetch(){
var url = "https://graph.facebook.com/125120007543580/feed&callback=?&limit=2";
var i = 0;
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url,function(json){
var html = "<div id=\"faceWall\">";
//loop through and within data array's retrieve the message variable.
$.each(json.data,function(i,fb){
var idTotal = fb.id;
var ids = idTotal.split("_");
var href = "http://www.facebook.com/"+ids[0]+"/posts/"+ids[1];
var msg = fb.message;
//adicionado
if (msg == undefined) {
msg = 'Cick here to see the post title';
} else if (msg.length > 150) {
msg = msg.substr(0,200)+"...";
}
//ISSUE HERE. IF I COMMENT THIS LINE ALL GOES WELL BUT NO PROFILE PICTURES ARE DISPLAYED.
if(fb.from)
html += "<img id=\"imagem"+i+"\" src=\"http://graph.facebook.com/" + fb.from.id + "/picture\"/>";
if(fb.to) {
$.each(fb.to.data, function(j,to_user) {
html += "<img id=\"imagem"+i+"-"+j+"\" src=\"http://graph.facebook.com/" + to_user.id + "/picture\"/>";
});
}
html += "<div id=\"textoFaceWall\">";
html += "<p id=\"msg"+i+"\">";
//adicionado fb.name em vez de fb.from.name:
if (fb.name == undefined) {
html += "" + fb.from.name + " - " + msg + "</p>";
} else {
html += "" + fb.name + " - " + msg + "</p>";
}
html += "<p class=\"dataPostWall\" id=\"data"+i+"\">"+ dataFinal + "</p> ";
html += "</p>";
html += "</div>";
html += "<img class=\"linhaHomePageCanais\" src=\""+baseUrl+"/lib/img/linhaWall.png\" alt=\"linha wall\"/>";
});
html += "</div>";
$("#coluna2").append(html);
});
};
fbFetch();
You may try this for PHP
$request_url = 'http://graph.facebook.com/redbull/picture?redirect=false';
$requests = file_get_contents($request_url);
$fb_response = json_decode($requests);
$imagen[]=$fb_response->data->url;
There you get the URL of the picture from the URL item in the JSON Graph api call.