RSS feed displaying NaN xml jquery - javascript

I am coding a simple RSS feed using jquery and a feed from wired. Everything is working great, but for some reason the result is including a NaN after the description. I cannot figure out what it is trying to pull, and since it is not wrapped in any tags, it follows a paragraph as such:
<p></p> NaN </div>
I cannot use css to hide it, and i dont want to limit the description length as some are longer than others and setting an arbitrary character limit may allow it to display anyways on shorter descriptions.
xml feed: http://www.wired.com/category/business/feed/
script:
(function ($) {
$.fn.FeedEk = function (opt) {
var def = $.extend({
FeedUrl: "http://www.wired.com/category/business/feed/",
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
TitleLinkTarget: "_blank",
}, opt);
var id = $(this).attr("id");
var i;
$("#" + id).empty().append('<img src="loader.gif" />');
$.ajax({
url: "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=" + def.MaxCount + "&output=json&q=" + encodeURIComponent(def.FeedUrl) + "&hl=en&callback=?",
dataType: "json",
success: function (data) {
$("#" + id).empty();
var s = "";
$.each(data.responseData.feed.entries, function (e, item) {
s += '<li><div class="itemTitle"><a href="' + item.link + '" target="' + def.TitleLinkTarget + '" >' + item.title + "</a></div>";
if (def.ShowPubDate) {
i = new Date(item.publishedDate);
s += '<div class="itemDate">' + i.toLocaleDateString() + "</div>";
}
if (def.ShowDesc) {
if (def.DescCharacterLimit > 0 && item.content.length > def.DescCharacterLimit) {
var StringStartAfterImage = item.content.indexOf('>',item.content.indexOf('< img')) + 1;
s += '<div class="itemContent">' + item.content.substr(0, def.DescCharacterLimit + StringStartAfterImage) + "..";
}
else {
s += '<div class="itemContent">' + item.content;
}
s += + "</div>";
}
});
$("#" + id).append('<ul class="feedEkList">' + s + "</ul>");
}
});
};
})(jQuery);
$(document).ready(function() {
$('#home-news').FeedEk({
FeedUrl: 'http://www.wired.com/category/business/feed/',
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
});
});
html:
<div class="newsCenter">
<div class="news">
<div id="home-news"> </div>
</div>
</div>
any help is much appreciated! Thank you!

i solved this by removing code after the else statement and closing the div in the else statement, i do not need the data that is not generating so this solution works for me.

Related

How to modify javascript to have html result instead of show out the html code in a comment system?

Currently,
when i input test,
the comment system directly show my typing, "test"
Modify to,
I would like the modify the javascript code that when i input test,
it convert to html result "test" (a hyperlink to "#").
How can i modify following code? Many thanks!
function fetchComments(leaveRequestId) {
$('#existingComments').html(lang_Loading);
params = 'leaveRequestId=' + leaveRequestId;
$.ajax({
type: 'GET',
url: getCommentsUrl,
data: params,
dataType: 'json',
success: function(data) {
var count = data.length;
var html = '';
var rows = 0;
$('#existingComments').html('');
if (count > 0) {
html = "<table class='table'><tr><th>" + lang_Date + "</th><th>" + lang_Time + "</th><th>" + lang_Author + "</th><th>" + lang_Comment + "</th></tr>";
for (var i = 0; i < count; i++) {
var css = "odd";
rows++;
if (rows % 2) {
css = "even";
}
var comment = $('<div/>').text(data[i]['comments']).html();
html = html + '<tr class="' + css + '"><td>' + data[i]['date'] + '</td><td>' + data[i]['time'] + '</td><td>' +
data[i]['author'] + '</td><td>' + comment + '</td></tr>';
}
html = html + '</table>';
} else {
}
$('#existingComments').append(html);
}
});
}
<div id="existingComments">
<span><?php echo __('Loading') . '...';?></span>
</div>
var comment = $('<div/>').text(data[i]['comments']).html();
You're explicitly escaping the data from the Ajax request so that it shows up as text and isn't treated as HTML source code.
If you don't want to do that, then just don't do it!
(Do be careful not to expose yourself to stored XSS attacks though)
$('#existingComments').html(html);

Multiple of the similar "Select Option" ID , Dynamic Javascript Code

1) I need to find a way to have multiple of id="select-repo" because every single "add another item" is the same. "Add Another Item" is suppose to add another row of html with that id="select-repo" for now it's just a empty textbox.
Generate Functions on the go? Dynamic Functions? I can easily loop the Select box but not the "$('#select-repo').selectize({" function i believe.
2) After number 1 is solved, I need to find a way to know which row of data to update after an option has been selected.
3) Is this easier to get done with VUE.JS, since i'm using laravel , integration should be easier with Vue.JS
What is your advice, I was told to use stuff like ReactJS / styled components? is there anyway to not switch framework to just get this done?
Please Advice.
HTML Code
<td><select id="select-repo" class="repositories"></select></td>
JS Code
<script>
//<select id="select-repo"></select>
$('#select-repo').selectize({
valueField: 'url',
labelField: 'name',
searchField: 'name',
options: [],
create: false,
render: {
option: function(item, escape) {
return '<div>' +
'<span class="title">' +
'<span class="name"><i class="icon ' + (item.fork ? 'fork' : 'source') + '"></i>' + escape(item.name) + '</span>' +
'<span class="by">' + escape(item.username) + '</span>' +
'</span>' +
'<span class="description">' + escape(item.description) + '</span>' +
'<ul class="meta">' +
(item.language ? '<li class="language">' + escape(item.language) + '</li>' : '') +
'<li class="watchers"><span>' + escape(item.watchers) + '</span> watchers</li>' +
'<li class="forks"><span>' + escape(item.forks) + '</span> forks</li>' +
'</ul>' +
'</div>';
}
},
score: function(search) {
var score = this.getScoreFunction(search);
return function(item) {
return score(item) * (1 + Math.min(item.watchers / 100, 1));
};
},
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: 'https://api.github.com/legacy/repos/search/' + encodeURIComponent(query),
type: 'GET',
error: function() {
callback();
},
success: function(res) {
callback(res.repositories.slice(0, 10));
}
});
},
onChange: function(value) {
alert(value);
}
});
</script>
Since id can not be the same, you can define a global variable like index to memo the count as part of id;
Like to dynamically add select with id "select-repo"+index; e.g. select-repo1, select-repo999
Here's an example:
var index = 1;
function addSelect(){
$('#somewhere').append('<select id="select-repo'+index+'">');
$('select-rep'+index).selectize(){
....
};
index++;
}
And you can easily get the select index by parse Id string.

Find and remove date in jQuery

I use RSS to get posts from my WordPress website and in its name have date in title and I want to remove the date from its title and use date from rss instead
The Result I want (image) I want to remove date on title (red cross) and use rss date(green underline) instead
The problem is date format in title is not international format
Any idea to make jQuery to detect this date formula and replace(remove) it?
HTML
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="http://momentjs.com/downloads/moment-with-langs.min.js"></script>
<script type="text/javascript" src="http://www.sd.ac.th/main/wp-content/rss_fetch/FeedEk.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#divRss').FeedEk({
FeedUrl: 'http://www.sd.ac.th/main/?feed=rss2&cat=121',
//FeedUrl: 'http://www.sd.ac.th/main/?feed=rss2&cat=234',
MaxCount: 10,
ShowPubDate: true,
ShowDesc: false
});
/*setInterval(function(){
$('.itemTitle a').each(function() {
var text = $(this).text();
$(this).text(text
.replace('[', '')
.replace(']', '')
.replace('59', '')
.replace('60', '')
);
});}
, 1);*/
});
function reloadFunction() {
location.reload();
}
</script>
<button onclick="reloadFunction()">R</button>
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="http://www.sd.ac.th/main/wp-content/rss_fetch/rss_style.css">
<div id="divRss"></div>
FeedEk.js (Plugin that I use for fetching my feed)
/*
* FeedEk jQuery RSS/ATOM Feed Plugin v3.0 with YQL API
* http://jquery-plugins.net/FeedEk/FeedEk.html https://github.com/enginkizil/FeedEk
* Author : Engin KIZIL http://www.enginkizil.com
*/
(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);
If it is always and the only thing between brackets ([ and ]) and it's always at the end of the string then use this:
text = text.replace(/(\[.*\])$/, replacementDateString);
Read about Regular Expression.

Appending content from RSS feeds to separate divs

I'm trying to display RSS using the following JS code. But when I execute this, both the RSS feeds are changed to same content (the one that is execute later) and all the feeds are appended to the same div. I think rss = this is causing the problem. Any workaround ?
HTML:
<div id="rss1" class="rss-widget">
<ul></ul>
</div>
<div id="rss2" class="rss-widget">
<ul></ul>
</div>
<div id="rss3" class="rss-widget">
<ul></ul>
</div>
JS:
function RSSWidget(id, url) {
rss = this;
rss.FEED_URL = url;
rss.JSON = new Array();
rss.widgetHolder = $('#' + id + ' ul ');
rss.storiesLimit = 15;
rss.renderBlogItem = function (object) {
var item = '<li class="blog-item">';
item += '<a href="' + object.link + '">';
item += '<div class="blog-item-title">' + object.title + '</div>';
item += '<div class="blog-item-author">' + object.author + '</div>';
// item += '<div class="blog-item-content">' + object.content + '</div>';
item += '</a>'
item += '</li>';
rss.widgetHolder.append(item);
}
return $.ajax({
url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(rss.FEED_URL),
dataType: 'json',
success: function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
rss.JSON.push({ //add objects to the array
title: e.title,
author: e.author,
content: e.content || "",
link: e.link
});
});
if (rss.storiesLimit > rss.JSON.length)
rss.storiesLimit = rss.JSON.length;
for (var i = 0; i < rss.storiesLimit; i++) {
rss.renderBlogItem(rss.JSON[i]);
}
$('#' + id + ' li ').each(function () {
var delay = ($(this).index() / rss.storiesLimit) + 's';
$(this).css({
webkitAnimationDelay: delay,
mozAnimationDelay: delay,
animationDelay: delay
});
});
}
}
});
}
$.when(RSSWidget('rss1', "http://rss.cnn.com/rss/money_markets.rss"))
.then(function () {
RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews")
})
.then(function () {
RSSWidget('rss3', "http://finance.yahoo.com/rss/topfinstories")
});
.then(RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews"));
is immediately invoked. Try calling second RSSWidget within .then() anonymous function
.then(function() {
RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews")
})
Also, no promise is returned from RSSWidget; you can include return $.ajax(/* settings */) from RSSWidget to return the jQuery promise object from RSSWidget.

JSON div style background image link doesn't have slashes?

I am creating a list of thumbnails with JSON and I have problem with this line of code:
videoHTML += '<div class="user-background" style="background-image: url("' + video.channel.video_banner + '");">';
I can see div element and everything in it except background-image link doesn't have slashes.
This is the code that I see in debugger elements:
<div class="user-background" style="background-image: url(" https:="" static-cdn.jtvnw.net="" jtv_user_pictures="" esl_csgo-channel_offline_image-c9f885982daa1c83-1920x1080.png");"=""><div class="user-background" style="background-image: url(" https:="" static-cdn.jtvnw.net="" jtv_user_pictures="" esl_csgo-channel_offline_image-c9f885982daa1c83-1920x1080.png");"=""><img class="user-logo" src="https://static-cdn.jtvnw.net/jtv_user_pictures/esl_csgo-profile_image-546a0c1883798a41-300x300.jpeg" alt="user image"><p class="user-name">ESL_CSGO</p></div><img class="video-image" src="http://static-cdn.jtvnw.net/previews-ttv/live_user_esl_csgo-320x180.jpg"><h1 class="game-name">Counter-Strike: Global Offensive</h1><br><i></i><span class="views-number">41304</span><p class="short-date-format date0">2012-06-11T13:36:21Z</p></div>
Can You help me by explaining what I am doing wrong with quotation marks?
(I believe that they are causing this problem.)
Here is the code for you to understand it better:
$(document).ready(function(){
$.getJSON( "https://api.twitch.tv/kraken/streams", function( data ) {
var items = [];
var videoHTML ='<ul>';
//Get data and create video grid
$.each(data.streams, function(i, video){
if(i < 9) { //get only first 9 data
var videoDate = $.format.date(video.channel.created_at, "MMM dd yyyy");
videoHTML += '<li class="video-stream ' + video.channel.language + '">';
videoHTML += '<div class="user-background" style="background-image: url("' + video.channel.video_banner + '");">';
videoHTML += '<img class="user-logo" src="' + video.channel.logo + '" alt="user image">';
videoHTML += '<p class="user-name">' + video.channel.display_name + '</p>';
videoHTML += '</div>';
videoHTML += '<a href="#" onclick="popup(\'' + video.channel.name + '\')">';
videoHTML += '<img class="video-image" src="' + video.preview.medium + '"></a>';
videoHTML += '<h1 class="game-name">' + video.game + '</h1><br/>';
videoHTML += '<i></i>';
videoHTML += '<span class="views-number">' + video.viewers + '</span>';
videoHTML += '<p class="short-date-format date' + i + '">' + videoDate + '</p>';
videoHTML += '</li>';
// var userId = "'#userBackground" + i +"'";
alert(userId);
// console.log(video._id);
// console.log(data.streams[i].game);
// console.log(data.streams[i]._links.self);
// console.log(data.streams[i].preview.medium);
} else {
return false;
}
});
videoHTML += '</ul>';
videoHTML += '<div class="clearfix"></div>';
$('#placeholder').html(videoHTML);
}); //getJson
}); //end ready
UPDATE I found your problem. You have to change the " around the style to \'. Like so:
videoHTML += '<div class="user-background" style=\'background-image: url("' + $.trim(video.channel.video_banner) + '");\'>';
See it working with your corrected code here.
I rewrote the whole thing and showed you a few fundamental features of jQuery. Keep in mind, it's not necessarily better, per say, but perhaps more effecient and easier to follow. Within JS alone, there's a dozen different ways to write this. Within jQuery, a million. I could easily have made this a lot shorter, and if for myself, I would do it MUCH different. However, I hope this shows you some of the different uses of jQuery, as well as understanding on why variable control can be so important. I actually didn't see charlietfl's code working. The background still doesn't show up. However, as you'll see in my example, not only did I narrow down to the "problem", I also made it work, but not with anything fancy. I just used basic jQuery!
Keep in mind, jQuery has a well written, easy to follow API. Everything I use here is easily find-able there!
CodeSnippet
function buildList(data) {
if (data) {
var videoHTML = $('<ul />'),
clearFix = $('<div />', { 'class': '' }),
items = [];
$.each(data.streams, function(i, video){
if(i < 9) {
var videoDate = video.channel.created_at, // $.format.date(video.channel.created_at, "MMM dd yyyy"),
li = $('<li />', { 'class': 'video-stream' }).addClass(video.channel.language).appendTo(videoHTML),
div = $('<div />', { 'class': 'user-background' }).appendTo(li),
imgLogo = $('<img />', { alt: 'user image', 'class': 'user-logo' }).attr('src', video.channel.logo).appendTo(div),
pUser = $('<p />', { 'class': 'user-name', html: video.channel.display_name }).appendTo(div),
a = $('<a />', { href: 'javascript:void 0' }).data('vidName', video.channel.name).appendTo(li),
imgPrev = $('<img />', { 'class': 'video-image' }).attr('src', video.preview.medium).appendTo(a),
h1 = $('<h1 />', { 'class': 'game-name' }).appendTo(li),
br = $('<br />').appendTo(li),
ita = $('<i />').appendTo(li),
span = $('<span />', { 'class': 'views-number' }).html(video.viewers).appendTo(li),
pDate = $('<p />', { 'class': 'short-date-format' }).addClass('date' + i).appendTo(li);
// And now we can zero in on your issue with ez, by moveing that one thing here
try {
console.log(video.channel.video_banner);
div.css('backgroundImage', 'url("' + video.channel.video_banner + '")');
}
catch(err) { console.log(err); }
}
else return false;
});
$('#placeholder').append(videoHTML, clearFix);
}
}
$(function() { // jQuery shorthand for $(document).ready(function(){
$.getJSON("https://api.twitch.tv/kraken/streams", buildList);
// the following uses our STATIC element to assign click event to our DYNAMICALLY added anchors
$('#placeholder').on('click', '.video-stream a', function(e) { popup($(this).data('vidName')); });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="placeholder"></div>
jsFiddle for playing!

Categories

Resources