Getting JSON Object then adding parts to HTML - javascript

I have been trying to get a script to work for my Github site and I am processing a JSON file to get an array to HTML in a ordered list.
My code I have been using is:
$(document).ready(function() {
$.getJSON("https://raw.githubusercontent.com/vvoid-inc/LillyPak-Starbound/gh-pages/mods/stable.json", function(data) {
$.each(mods, function(i) {
var tempUrl = "";
var tempApproved = "";
if (data.mods[i].Repo[0] == 0) {
tempUrl = data.mods[i].Repo[1];
} else if (data.mods[i].Repo[0] == 1) {
tempUrl = "http://community.playstarbound.com/resources/" + data.mods[i].Repo[1] + "/";
} else {
tempUrl = data.mods[i].Repo[1];
}
if (data.mods[i].Approved == true) {
tempApproved = "checked";
} else {
tempApproved = "";
}
$("#modsList").append("<li><a href='" + tempUrl + "'>" + data.mods[i].Title + "</a> - by " + data.mods[i].Author + "<ul><li>\t- <input type='checkbox' " + tempApproved + "/> Approved</li></ul></li>");
});
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol id="modsList"></ol>
So what have I been doing wrong because nothing is working...

This should work:
$(document).ready(function() {
$.getJSON("https://raw.githubusercontent.com/vvoid-inc/LillyPak-Starbound/gh-pages/mods/stable.json", function(data) {
$.each(data.mods, function(i, m) {
var tempUrl = "";
var tempApproved = "";
if (m.Repo[0] == 0) {
tempUrl = m.Repo[1];
} else if (m.Repo[0] == 1) {
tempUrl = "http://community.playstarbound.com/resources/" + m.Repo[1] + "/";
} else {
tempUrl = m.Repo[1];
}
if (m.Approved == true) {
tempApproved = "checked";
} else {
tempApproved = "";
}
$("#modsList").append("<li><a href='" + tempUrl + "'>" + m.Title + "</a> - by " + m.Author + "<ul style='list-style-type:none'><li>\t - <input type='checkbox' " + tempApproved + " disabled/> Approved</li></ul></li>");
});
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol id="modsList"></ol>
Instead of $.each(mods, function(i) { it should be $.each(data.mods, function(i, m) {. and the mods[i]. should be m..
Also there was a formatting error in the JSON file but now it is fixed. It was causing the errors to not display.

Related

Clear previous results from query

Through the attached code I do a search on youtube based on the username and the results are shown. If I search twice, the results add up. I would like previous results to be deleted. I try with htmlString = card; but it show only one result.Thanks to everyone who wants to help me solve this problem.
var musicCards = [];
jQuery(document).ready(function() {
jQuery("#searchButton").on("click", function() {
var query = jQuery("#queryInput").val();
if (query != "") {
loadYoutubeService(query);
console.log(query + "");
}
});
});
function loadYoutubeService(query) {
gapi.client.load('youtube', 'v3', function() {
gapi.client.setApiKey('ADADADADADA');
search(query);
});
}
function search(query) {
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: query,
type: 'channel',
maxResults: 15
});
request.execute(function(response) {
jQuery.each(response.items, function(i, item) {
if (!item['']) {
var musicCard = {};
musicCard._id = item['snippet']['customUrl'];
musicCard.title = item['snippet']['title'];
musicCard.linkprofilo = item['snippet']['channelId'];
musicCard.url = "https://www.youtube.com/channel/";
musicCard.description = item['snippet']['description'];
musicCard.immagine = item['snippet']['thumbnails']['high']['url'];
musicCards.push(musicCard);
}
});
renderView();
});
}
function renderView() {
var htmlString = "";
musicCards.forEach(function(musicCard, i) {
var card = createCard(musicCard._id, musicCard.title, musicCard.description, musicCard.url,musicCard.immagine, musicCard.linkprofilo);
htmlString += card;
});
jQuery('#youtube-utente').html(htmlString);
}
function createCard(_id, title, description, url, immagine, linkprofilo) {
var card =
'<div class="card">' +
'<div class="info">' +
'<img src="' + immagine + '" alt="' + description + '">' +
'</div>' +
'<div class="content">Clicca per selezionare:' +
'<h3>' + title + '</h3>' +
'<a class="seleziona" href="' + url +linkprofilo+'">'+ url +linkprofilo+'</a>' +
'<p>' + description + '</p>' +
'</div>' +
'</div>';
return card;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
Solved using :
request.execute(function(response) {
musicCards.length = 0; // clear array

I have javascript code to view a news from RSS as a vertical list. I need help to move the list of topics as horizontal one by one, in one line

I have javascript code to view a news from RSS as a vertical list.
(function ($) {
$.fn.FeedEk = function (opt) {
var def = $.extend({
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
DescCharacterLimit: 0,
TitleLinkTarget: "_blank",
DateFormat: "",
DateFormatLang:"en"
}, opt);
var id = $(this).attr("id"), i, s = "", dt;
$("#" + id).empty();
if (def.FeedUrl == undefined) return;
$("#" + id).append('<img src="loader.gif" />');
var YQLstr = 'SELECT channel.item FROM feednormalizer WHERE output="rss_2.0" AND url ="' + def.FeedUrl + '" LIMIT ' + def.MaxCount;
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(YQLstr) + "&format=json&diagnostics=false&callback=?",
dataType: "json",
success: function (data) {
$("#" + id).empty();
if (!(data.query.results.rss instanceof Array)) {
data.query.results.rss = [data.query.results.rss];
}
$.each(data.query.results.rss, function (e, itm) {
s += '<li><div class="itemTitle"><a href="' + itm.channel.item.link + '" target="' + def.TitleLinkTarget + '" >' + itm.channel.item.title + '</a></div>';
if (def.ShowPubDate){
dt = new Date(itm.channel.item.pubDate);
s += '<div class="itemDate">';
if ($.trim(def.DateFormat).length > 0) {
try {
moment.lang(def.DateFormatLang);
s += moment(dt).format(def.DateFormat);
}
catch (e){s += dt.toLocaleDateString();}
}
else {
s += dt.toLocaleDateString();
}
s += '</div>';
}
if (def.ShowDesc) {
s += '<div class="itemContent">';
if (def.DescCharacterLimit > 0 && itm.channel.item.description.length > def.DescCharacterLimit) {
s += itm.channel.item.description.substring(0, def.DescCharacterLimit) + '...';
}
else {
s += itm.channel.item.description;
}
s += '</div>';
}
});
$("#" + id).append('<ul class="feedEkList">' + s + '</ul>');
}
});
};
})(jQuery);
I need help to move the list of topics as horizontal one by one, in one line. by used javascript code. this code display just 5 topics, which I need it, but I have problem to how can I movement it as horizontal.

Facebook Graph API get original picture size not working

Need some help to get a normal or larger image from posts using the Facebook Graph API, at the moment it only gives a 130 x 130 px image in the object.
function fbFetch() {
var access_token = "";
var url = "https://graph.facebook.com/?ids=intel&fields=posts.limit(5){message,created_time,picture.type(normal)}&access_token=' + access_token;
$.getJSON(url, function(response) {
var messages = [];
Object.getOwnPropertyNames(response).forEach(function(page, idx, array) {
response[page].posts.data.forEach(function(post, idx, array) {
messages.push(post);
});
});
function compare(a, b) {
if (a.created_time < b.created_time)
return -1;
if (a.created_time > b.created_time)
return 1;
return 0;
}
var html = "<ul>";
$.each(messages.sort(compare), function(i, fb) {
if (typeof fb.picture != "undefined") {
html += "<li>" + fb.message + "</br>" + '<img SRC="' + fb.picture + '">' + "</br>" + fb.created_time + "</li></br>";
} else {
html += "<li>" + fb.message + "</br>" + fb.created_time + "</li></br>";
}
});
html += "</ul>";
$('.facebookfeed').html(html);
});
}
fbFetch();
<div class="facebookfeed"></div>
Fiddle here: http://jsfiddle.net/6fhq3dat/17/
use full_picture instead of picture
var url = "https://graph.facebook.com/?ids=intel&fields=posts.limit(3){message,created_time,full_picture}&access_token=" + access_token;
demo

Unexpected token } can not find the mistake

i tried everything but i don't know where the mistake should be its show me a unespekted token } in a line where i not even have this sign.
<script type="text/javascript">
function postToStatus(action,type,user,ta){
var data = _(ta).value;
if(data == ""){
alert("Type something first weenis");
return false;
}
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/qp_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "post_ok"){
var sid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g," ><br />").replace(/\r/g,"<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_'+sid+
'class="status_boxes"><div><b>Posted by you just now:</b><span >id="sdb_'+sid+
'"><a href="#" onclick="return false" >onmousedown="deleteStatus("'+sid+
'\',\'status_'+sid+
'\');" title="DELETE THIS STATUS AND ITS REPLIES">delete status</a> ></span><br />'+data+
'</div></div>"'+currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action="+action+"&type="+type+"&user="+user+"&data="+data);
}
You need to put a semi-colon after the last } just before the ajax.send() call.
This website is your best friend if you write JavaScript: http://closure-compiler.appspot.com/home
function postToStatus(action, type, user, ta) {
var data = _(ta).value;
if (data == "") {
alert("Type something first weenis");
return false;
}
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/qp_system.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if (datArray[0] == "post_ok") {
var sid = datArray[1];
data = data.replace(/</g, "<").replace(/>/g, ">").replace(/\n/g, " ><br />").replace(/\r/g, "<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_' + sid + 'class="status_boxes"><div><b>Posted by you just now:</b><span >id="sdb_' + sid + '">delete status ></span><br />' + data + '</div></div>"' + currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
};
ajax.send("action=" + action + "&type=" + type + "&user=" + user + "&data=" + data);
}
;

Extension stopped working with Google Chrome manifest v2

I am developing an extension for Google Chrome that was working perfectly, but now stopped working with version 2 of the manifest.
It is giving me the following error:
Uncaught SyntaxError: Unexpected end of input
popup.js:
chrome.tabs.getSelected(null, function (aba) {
link = aba.url;
titulo = aba.title;
document.getElementById('mensagem').value = link;
});
function GrabIFrameURL(feedDescription) {
var regex = new RegExp("iframe(?:.*?)src='(.*?)'", 'g');
var matches = regex.exec(feedDescription);
var url = '';
if (matches.length == 2) {
url = matches[1];
}
var quebra = url.split("/");
return quebra[4];
}
$(document).ready(function () {
if (localStorage.nome == '' || localStorage.nome == null || localStorage.email == '' || localStorage.email == null) {
jQuery('#formulario').hide();
jQuery('#erros').html('Configure seus dados aqui');
}
jQuery("#resposta").ajaxStart(function () {
jQuery(this).html("<img src='img/loading.gif'> <b>Sugestão sendo enviada, aguarde...</b>");
});
jQuery('#submit').click(function () {
var nome = localStorage.nome;
var email = localStorage.email;
var mensagem = titulo + "\n\n<br><br>" + link;
jQuery('#formulario').hide();
jQuery.post('http://blabloo.com.br/naosalvo/mail.php', {
nome: nome,
email: email,
mensagem: mensagem
},
function (data, ajaxStart) {
jQuery('#resposta').html(data);
console.log(data);
});
return false;
});
//Listagem de posts
var bkg = chrome.extension.getBackgroundPage();
jQuery('#close').click(function () {
window.close();
});
jQuery('#markeall').click(function () {
bkg.lidoAll();
$('.naolido').attr('class', 'lido');
});
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
$('.naolido').click(function (e) {
e.preventDefault();
klicked = $(this).attr('id');
console.log(klicked);
bkg.setLido(klicked);
$(this).attr('class', 'lido');
openLink($(this).attr('href'));
});
$('.lido').click(function (e) {
openLink($(this).attr('href'));
});
var openLink = function (link) {
chrome.tabs.create({
'url': link,
'selected': true
});
window.close();
}
});
I think the problem is in this part of popup.js:
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
You problem is actually in background.js on lines 12 and 20, you set localStorage.items to '' initially but then try to run a JSON.parse() on it later, but it's not JSON data so JSON.parse returns Unexpected end of input. And, JSON.parse isn't a function you define but a native browser function so, it shows the error as being on "line 1".
Try defining it as an empty array initially and then "pushing" to it as you are now.

Categories