How to parse an RSS feed using JavaScript? - javascript

I need to parse an RSS feed (XML version 2.0) and display the parsed details in an HTML page.

Parsing the Feed
With jQuery's jFeed
(Don't really recommend that one, see the other options.)
jQuery.getFeed({
url : FEED_URL,
success : function (feed) {
console.log(feed.title);
// do more stuff here
}
});
With jQuery's Built-in XML Support
$.get(FEED_URL, function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
With jQuery and the Google AJAX Feed API
$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(FEED_URL),
dataType : 'json',
success : function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});
But that means you're relient on them being online and reachable.
Building Content
Once you've successfully extracted the information you need from the feed, you could create DocumentFragments (with document.createDocumentFragment() containing the elements (created with document.createElement()) you'll want to inject to display your data.
Injecting the content
Select the container element that you want on the page and append your document fragments to it, and simply use innerHTML to replace its content entirely.
Something like:
$('#rss-viewer').append(aDocumentFragmentEntry);
or:
$('#rss-viewer')[0].innerHTML = aDocumentFragmentOfAllEntries.innerHTML;
Test Data
Using this question's feed, which as of this writing gives:
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:re="http://purl.org/atompub/rank/1.0">
<title type="text">How to parse a RSS feed using javascript? - Stack Overflow</title>
<link rel="self" href="https://stackoverflow.com/feeds/question/10943544" type="application/atom+xml" />
<link rel="hub" href="http://pubsubhubbub.appspot.com/" />
<link rel="alternate" href="https://stackoverflow.com/q/10943544" type="text/html" />
<subtitle>most recent 30 from stackoverflow.com</subtitle>
<updated>2012-06-08T06:36:47Z</updated>
<id>https://stackoverflow.com/feeds/question/10943544</id>
<creativeCommons:license>http://www.creativecommons.org/licenses/by-sa/3.0/rdf</creativeCommons:license>
<entry>
<id>https://stackoverflow.com/q/10943544</id>
<re:rank scheme="http://stackoverflow.com">2</re:rank>
<title type="text">How to parse a RSS feed using javascript?</title>
<category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="javascript"/><category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="html5"/><category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="jquery-mobile"/>
<author>
<name>Thiru</name>
<uri>https://stackoverflow.com/users/1126255</uri>
</author>
<link rel="alternate" href="https://stackoverflow.com/questions/10943544/how-to-parse-a-rss-feed-using-javascript" />
<published>2012-06-08T05:34:16Z</published>
<updated>2012-06-08T06:35:22Z</updated>
<summary type="html">
<p>I need to parse the RSS-Feed(XML version2.0) using XML and I want to display the parsed detail in HTML page, I tried in many ways. But its not working. My system is running under proxy, since I am new to this field, I don't know whether it is possible or not. If any one knows please help me on this. Thanks in advance.</p>
</summary>
</entry>
<entry>
<id>https://stackoverflow.com/questions/10943544/-/10943610#10943610</id>
<re:rank scheme="http://stackoverflow.com">1</re:rank>
<title type="text">Answer by haylem for How to parse a RSS feed using javascript?</title>
<author>
<name>haylem</name>
<uri>https://stackoverflow.com/users/453590</uri>
</author>
<link rel="alternate" href="https://stackoverflow.com/questions/10943544/how-to-parse-a-rss-feed-using-javascript/10943610#10943610" />
<published>2012-06-08T05:43:24Z</published>
<updated>2012-06-08T06:35:22Z</updated>
<summary type="html"><h1>Parsing the Feed</h1>
<h3>With jQuery's jFeed</h3>
<p>Try this, with the <a href="http://plugins.jquery.com/project/jFeed" rel="nofollow">jFeed</a> <a href="http://www.jquery.com/" rel="nofollow">jQuery</a> plug-in</p>
<pre><code>jQuery.getFeed({
url : FEED_URL,
success : function (feed) {
console.log(feed.title);
// do more stuff here
}
});
</code></pre>
<h3>With jQuery's Built-in XML Support</h3>
<pre><code>$.get(FEED_URL, function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
</code></pre>
<h3>With jQuery and the Google AJAX APIs</h3>
<p>Otherwise, <a href="https://developers.google.com/feed/" rel="nofollow">Google's AJAX Feed API</a> allows you to get the feed as a JSON object:</p>
<pre><code>$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&amp;num=10&amp;callback=?&amp;q=' + encodeURIComponent(FEED_URL),
dataType : 'json',
success : function (data) {
if (data.responseData.feed &amp;&amp; data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});
</code></pre>
<p>But that means you're relient on them being online and reachable.</p>
<hr>
<h1>Building Content</h1>
<p>Once you've successfully extracted the information you need from the feed, you need to create document fragments containing the elements you'll want to inject to display your data.</p>
<hr>
<h1>Injecting the content</h1>
<p>Select the container element that you want on the page and append your document fragments to it, and simply use innerHTML to replace its content entirely.</p>
</summary>
</entry></feed>
Executions
Using jQuery's Built-in XML Support
Invoking:
$.get('https://stackoverflow.com/feeds/question/10943544', function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
Prints out:
------------------------
title : How to parse a RSS feed using javascript?
author :
Thiru
https://stackoverflow.com/users/1126255
description:
------------------------
title : Answer by haylem for How to parse a RSS feed using javascript?
author :
haylem
https://stackoverflow.com/users/453590
description:
Using jQuery and the Google AJAX APIs
Invoking:
$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('https://stackoverflow.com/feeds/question/10943544'),
dataType : 'json',
success : function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});
Prints out:
------------------------
title : How to parse a RSS feed using javascript?
author : Thiru
description: undefined
------------------------
title : Answer by haylem for How to parse a RSS feed using javascript?
author : haylem
description: undefined

Another deprecated (thanks to #daylight) option, and the easiest for me (this is what I'm using for SpokenToday.info):
The Google Feed API without using JQuery and with only 2 steps:
Import the library:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("feeds", "1");</script>
Find/Load feeds (documentation):
var feed = new google.feeds.Feed('http://www.google.com/trends/hottrends/atom/feed?pn=p1');
feed.load(function (data) {
// Parse data depending on the specified response format, default is JSON.
console.dir(data);
});
To parse data, check documentation about the response format.

If you are looking for a simple and free alternative to Google Feed API for your rss widget then rss2json.com could be a suitable solution for that.
You may try to see how it works on a sample code from the api documentation below:
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("https://news.ycombinator.com/rss");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(initialize);
<html>
<head>
<script src="https://rss2json.com/gfapi.js"></script>
</head>
<body>
<p><b>Result from the API:</b></p>
<div id="feed"></div>
</body>
</html>

If you want to use a plain javascript API, there is a good example at https://github.com/hongkiat/js-rss-reader/
The complete description at https://www.hongkiat.com/blog/rss-reader-in-javascript/
It uses fetch method as a global method that asynchronously fetches a resource. Below is a snap of code:
fetch(websiteUrl).then((res) => {
res.text().then((htmlTxt) => {
var domParser = new DOMParser()
let doc = domParser.parseFromString(htmlTxt, 'text/html')
var feedUrl = doc.querySelector('link[type="application/rss+xml"]').href
})
}).catch(() => console.error('Error in fetching the website'))

For anyone else reading this (in 2019 onwards) unfortunately most JS RSS reading implementations don't now work. Firstly Google API has shut down so this is no longer an option and because of the CORS security policy you generally cannot now request RSS feeds cross-domains.
Using the example on https://www.raymondcamden.com/2015/12/08/parsing-rss-feeds-in-javascript-options (2015) I get the following:
Access to XMLHttpRequest at 'https://feeds.feedburner.com/raymondcamdensblog?format=xml' from origin 'MYSITE' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is correct and is a security precaution by the end website but does now mean that the answers above are unlikely to work.
My workaround will probably be to parse the RSS feed through PHP and allow the javascript to access my PHP rather than trying to access the end-destination feed itself.

I was so exasperated by many misleading articles and answers that I wrote my own RSS reader:
https://gouessej.wordpress.com/2020/06/28/comment-creer-un-lecteur-rss-en-javascript-how-to-create-a-rss-reader-in-javascript/
You can use AJAX requests to fetch the RSS files but it will work if and only if you use a CORS proxy. I'll try to write my own CORS proxy to give you a more robust solution. In the meantime, it works, I deployed it on my server under Debian Linux.
My solution doesn't use JQuery, I use only plain Javascript standard APIs with no third party libraries and it's supposed to work even with Microsoft Internet Explorer 11.

You can use jquery-rss or Vanilla RSS, which comes with nice templating and is super easy to use:
// Example for jquery.rss
$("#your-div").rss("https://stackoverflow.com/feeds/question/10943544", {
limit: 3,
layoutTemplate: '<ul class="inline">{entries}</ul>',
entryTemplate: '<li>[{author}#{date}] {title}<br/>{shortBodyPlain}</li>'
})
// Example for Vanilla RSS
const RSS = require('vanilla-rss');
const rss = new RSS(
document.querySelector("#your-div"),
"https://stackoverflow.com/feeds/question/10943544",
{
// options go here
}
);
rss.render().then(() => {
console.log('Everything is loaded and rendered');
});
See http://jsfiddle.net/sdepold/ozq2dn9e/1/ for a working example.

Trying to find a good solution for this now, I happened upon the FeedEk jQuery RSS/ATOM Feed Plugin that does a great job of parsing and displaying RSS and Atom feeds via the jQuery Feed API. For a basic XML-based RSS feed, I've found it works like a charm and needs no server-side scripts or other CORS workarounds for it to run even locally.

I did not find a solution for parsing RSS just with js due to CORS error I kept receiving. Installing a plugin is not an option for me and building a proxy is not fun either and the small solutions I found didn't work.
So just in case someone is getting here and can use server-side, I found this solution in PHP that worked for me perfectly! (without the CORS error! "x has been blocked by CORS policy...")

Related

Run a JS script conditionally from a web source

I am making a website that grabs data from an API. The API essentially consists of a script normally ran as such
<script type="text/javascript" src="https://www.fxblue.com/users/dynascalp_demo/overviewscript"></script>
it will simply create an array and push the data I need from it, like this:
if (!document.MTIntelligenceAccounts) document.MTIntelligenceAccounts = new Array(); document.MTIntelligenceAccounts.push({ "userid": "dynascalp_demo","balance": 9275.95,"equity": 9275.95,"closedProfit": -724.05,"floatingProfit": 0,"freeMargin": 9275.95,"totalDeposits": 10000,"totalWithdrawals": 0,"totalBankedGrowth": -7.24,"monthlyBankedGrowth": -0.67,"weeklyBankedGrowth": -0.16,"dailyBankedGrowth": -0.03,"bankedProfitFactor": 0.66,"deepestValleyCash": -819.04,"deepestValleyPercent": -8.19,"troughInBalance": 9175.79,"peakInBalance": 10020.11,"historyLengthDays": 331,"averageTradeDurationHours": 2.17,"worstDayPercentage": -1.44,"worstWeekPercentage": -2.32,"worstMonthPercentage": -4.31,"tradesPerDay": 2.5,"totalClosedPositions": 589,"totalOpenPositions": 0,"bankedWinningTrades": 382,"bankedLosingTrades": 207,"bankedBreakEvenTrades": 0,"bankedWinPips": 1486.3,"bankedLossPips": -1604.6,"initialDeposit": 10000,"totalBankedPips":-118.3,"totalOpenPips":0,"peakPercentageLossFromOutset": -8.24,"riskReturnRatio": -1.21,"openAndPendingOrders": []});
My idea is to run this code conditionally, in another, bigger script. I will query my database and check whether the data is already in the database. If it is, then skip the request altogether and send the data from the database through an ajax request handled by the server, which will return a JSON. If it isn't or the data has expired, meaning it has not been updated for at least a day, it should grab the data from the API and update the database. This is done by the front-end as there is no Node.js support in the back-end.
The only thing I'm missing is how I should execute this script from mine, instead of calling it directly in the HTML.
For example, Fetch() does not work. I believe the request is malformed, or it is not the type of request it expects. Unexpected end of input is thrown and the request does not succeed.
This code should result in a number being shown
function fxBlue_retrieveAPI() {
document.MTIntelligenceAccounts = new Array();
const url = "https://www.fxblue.com/users/dynascalp_demo/overviewscript";
//var fxblue_API_Names = ["dynascalp_demo", "fxprogoldrobot", "fxprosilverrobot", "forex_gump_ea"];
var varNames = ["totalDeposits", "balance", "totalBankedGrowth", "monthlyBankedGrowth", "deepestValleyPercent", "historyLengthDays"];
var experts = [];
var s = document.createElement("script");
s.setAttribute("type", "text/javascript");
s.setAttribute("src", url);
document.body.appendChild(s);
for (var i = 0; i < document.MTIntelligenceAccounts.length; i++) {
experts.push({ name: document.MTIntelligenceAccounts[i].userid, id: i });
if (document.getElementById(experts[i].name + varNames[0])) { document.getElementById(experts[i].name + varNames[0]).innerHTML = document.MTIntelligenceAccounts[experts[i].id].totalDeposits; }
if (document.getElementById(experts[i].name + varNames[1])) { document.getElementById(experts[i].name + varNames[1]).innerHTML = document.MTIntelligenceAccounts[experts[i].id].balance; }
if (document.getElementById(experts[i].name + varNames[2])) { document.getElementById(experts[i].name + varNames[2]).innerHTML = document.MTIntelligenceAccounts[experts[i].id].totalBankedGrowth + "%" };
if (document.getElementById(experts[i].name + varNames[3])) { document.getElementById(experts[i].name + varNames[3]).innerHTML = document.MTIntelligenceAccounts[experts[i].id].monthlyBankedGrowth };
if (document.getElementById(experts[i].name + varNames[4])) { document.getElementById(experts[i].name + varNames[4]).innerHTML = document.MTIntelligenceAccounts[experts[i].id].deepestValleyPercent + "%" };
if (document.getElementById(experts[i].name + varNames[5])) { document.getElementById(experts[i].name + varNames[5]).innerHTML = document.MTIntelligenceAccounts[experts[i].id].historyLengthDays };
}
}
<script type="text/javascript" src="/cdn-cgi/scripts/API/jquery-3.1.1.min.js" async></script>
<script type="text/javascript" src="/cdn-cgi/scripts/API/test.js"></script>
<body onload="fxBlue_retrieveAPI()">
<h3>Total banked growth data example</h3>
<p id="dynascalp_demototalBankedGrowth"></p>
</body>
Assuming (or hoping) that you won't experience CORS problems with your data source (here at SO it is not possible to reach the source), you could do something like this to get to the actual contents of the script file:
const actualText=`if (!document.MTIntelligenceAccounts) document.MTIntelligenceAccounts = new Array();\ndocument.MTIntelligenceAccounts.push({\n"userid": "dynascalp_demo","balance": 9275.95,"equity": 9275.95,"closedProfit": -724.05,"floatingProfit": 0,"freeMargin": 9275.95,"totalDeposits": 10000,"totalWithdrawals": 0,"totalBankedGrowth": -7.24,"monthlyBankedGrowth": -0.67,"weeklyBankedGrowth": -0.16,"dailyBankedGrowth": -0.03,"bankedProfitFactor": 0.66,"deepestValleyCash": -819.04,"deepestValleyPercent": -8.19,"troughInBalance": 9175.79,"peakInBalance": 10020.11,"historyLengthDays": 331,"averageTradeDurationHours": 2.17,"worstDayPercentage": -1.44,"worstWeekPercentage": -2.32,"worstMonthPercentage": -4.31,"tradesPerDay": 2.5,"totalClosedPositions": 589,"totalOpenPositions": 0,"bankedWinningTrades": 382,"bankedLosingTrades": 207,"bankedBreakEvenTrades": 0,"bankedWinPips": 1486.3,"bankedLossPips": -1604.6,"initialDeposit": 10000,"totalBankedPips":-118.3,"totalOpenPips":0,"peakPercentageLossFromOutset": -8.24,"riskReturnRatio": -1.21,"openAndPendingOrders": []});`;
// fetch("https://www.fxblue.com/users/dynascalp_demo/overviewscript")
fetch("https://jsonplaceholder.typicode.com/users/3") // (some dummy data source for demo purposes only)
.then(r=>r.text())
.then(text=>{ text=actualText; // mimmic the text received from www.fxblue.com ...
obj=JSON.parse(text.replace(/(?:.|\n)*push\(/,"").replace(/\);$/,""))
console.log(obj)
})
It is then up to you to decide whether you want to use the data or not.
Whatever you do, it is important that the action happens in the callback function of the last . then() call. Alternatively you can of course also work with an async function and use await inside.
My idea is to run this javascript code conditionally, by querying my database
For this you could do an jquery ajax call, and act based on the response you get. I recommend using jquery for the ajax call. Here is the jquery ajax call where you pass whatever data is necessary to the controller.
$.ajax({
type: "GET",
url: "/ControllerName/ActionName",
data: { data: UserIdOrSomething },
success: function(response) {
// you can check the response with an if, and implement your logic here.
}
});
You can place this ajax call in the document.ready function to automatically call it whenever the page loads.
$( document ).ready(function() {
// place the above code here.
});
As an example, here is how an asp.net core controller action would look like that would handle this ajax call;
[HttpGet("ActionName/{data:string}")]
public IActionResult ActionName(string data) // parameter name should match the one in jquery ajax call
{
// do stuff. query your database etc.
var response = "the response";
return Json(response);
}
finally, keep in mind handling sensitive data in javascript is generally not a good idea, as the javascript code is open to everyone. For example, in this case, you will be giving out a way for people to check if a user exists in your database, which could be problematic. I would suggest using guid as id for the users table if possible, which may or may not be useful to mitigate the dangers depending on how you query the database.

JavaScript function being blocked by office addin

I have an outlook add-in that I have created. In this add-in I am trying to make a button pull some data from a website using APIs.
I was able to do this on with a local test but when I put the code into my add-in nothing happens. It gives an error in the console that says Tracking Prevention blocked access to storage for https://appsforoffice.microsoft.com/lib/1/hosted/en-us/outlook_strings.js. but when I commented out my javascript code, that error still came up. So I don't know why my code is being blocked.
Picture of problem:
On my local computer it works no problem:
Here is my code:
javascript:
function freshdesktickets() {
Office.onReady((info) => {
// window.parent.location.reload()
const url = "https://alloysystems.freshdesk.com/api/v2/tickets";
fetch(url, {
method: "GET",
withCredentials: true,
headers: {
// needed to base64 encode my key with ":x" at the end of the api key then I used that for the authorization header.
"authorization": "Basic YOUWILLNEVERGETMYAPIKEYLOL"
}
})
.then(resp => resp.json())
.then(data => {let text = "";
const output = document.querySelector('span.ms-font-m');
for (let i = 0; i < data.length; i++) {
let text = "Subject: " + JSON.stringify(data[i].subject) + "<br>"+
"CC Emails: " + JSON.stringify(data[i].cc_emails).replace("[]","No Emails are CC'd").replace("[","").replace("]","") + "<br>" +
"Ticket Creation Date: " + JSON.stringify(data[i].created_at) + "<br>" +
"Ticket Status: " + JSON.stringify(data[i].status).replace("2", "Open").replace("3", "Pending").replace("4", "Resolved").replace("5", "Closed").replace("6", "Waiting On Customer") ;
let pre = document.createElement('pre');
pre.innerHTML = text;
pre.style.cssText += 'font-size:24px;font-weight:bold;'
output.appendChild(pre);
console.log(pre)
}
})})
}
HTML:
<div class="ms-PanelExample">
<script src="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/js/fabric.min.js"></script>
<button style="margin:1px;" id="get-freshdesk" class="ms-Button ms-Button--primary">
<span class="ms-Button-label">Freshdesk Tickets</span>
</button>
<div class="ms-Panel ms-Panel--xxl">
<button class="ms-Panel-closeButton ms-PanelAction-close">
<i class="ms-Panel-closeIcon ms-Icon ms-Icon--Cancel"></i>
</button>
<div class="ms-Panel-contentInner">
<p class="ms-Panel-headerText">Freshdesk Integration</p>
<div class="ms-Panel-content">
<span class="ms-font-m">Latest Ticket information</span>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var PanelExamples = document.getElementsByClassName("ms-PanelExample");
for (var i = 0; i < PanelExamples.length; i++) {
(function() {
var PanelExampleButton = PanelExamples[i].querySelector(".ms-Button");
var PanelExamplePanel = PanelExamples[i].querySelector(".ms-Panel");
PanelExampleButton.addEventListener("click", function(i) {
new fabric['Panel'](PanelExamplePanel);
});
}());
}
</script>
Result from console:
Tracking Prevention blocked access to storage for https://appsforoffice.microsoft.com/lib/1/hosted/en-us/outlook_strings.js.
### yet it displays the pre information in the console below because I added console.log(pre)
I also tried adding the domains of where the api gets its data but I am still getting the error. I added it to the edge's exclusion list and I also added it to the manifest xml.
code that was added to the manifest xml to ensure that the api's domain is allow to get some data:
<!-- Domains that will be allowed when navigating. For example, if you use ShowTaskpane and then have an href link, navigation will only be allowed if the domain is on this list. -->
<AppDomains>
<AppDomain>https://freshdesk.com</AppDomain>
<AppDomain>https://alloysystems.freshdesk.com</AppDomain>
<AppDomain>AppDomain3</AppDomain>
</AppDomains>
<!--End Basic Settings. -->
I think I figured out the answer. The problem is that I added the javascript to my existing office apps javascript which has Office.onReady((info) => at the top of the script. If I add my javascript to the existing office apps javascript it will fail.
So I made a new javascript file and added that to the html. In the new file I used the javascript code above, then I simply added the script to the head tag and it started working.

Embed dynamically updated blog RSS Feed to Website

I have a website on one domain, and a blog hosted on blogspot. at the bottom of the homepage on my website, I want to embed a link to the latest post on my blogspot along with the respective article image and title. I have a function that used to work but since i have moved to blogspot, the RSS url is different from what i previously used, thus the function will not work as expected anymore. How can I work this function around the blogspot rss embed link ?? thanks
blogspot rss2.0 embed link
RSS 2.0: http://blogname.blogspot.com/feeds/posts/default?alt=rss
existing function:
<script src="js/jquery.min.js" type="text/javascript"></script>
<script>
function getRSS(link, number) {
$.ajax(link, {
accepts:{
xml:"application/rss+xml"
},
dataType:"xml",
success:function(data) {
var blogItemArray = $(data).find("item");
var blogItemOne = $(blogItemArray).get(0);
var blogTitleOne = $(blogItemOne).find("title").text();
var blogLinkOne = $(blogItemOne).find("link").text();
var blogDescOne = $(blogItemOne).find("description").text();
var blogImgOne = $(blogDescOne).find("img.hs-featured-image").get();
var blogImgSrcOne = $(blogImgOne).attr("src");
$("#blog-feed-link-" + number).attr("href", blogLinkOne);
$(".vertAlignerImg" + number).append( $('<img class="blog-img-link-'+ number +'" />' ));
$(".blog-img-link-" + number).attr("src", blogImgSrcOne);
$(".vertAligner" + number).append( $('<h2 />', {text: blogTitleOne}) );
}
});
}
$(document).ready(function() {
getRSS('rsslink', "One");
getRSS('rsslink', "Two");
});
</script>
'rsslink' used to be a url that ended in /rss.xml. now it looks like the link above. thanks!

Create Dropdown list from API Query

Attempting to create a script that will pull information from an API requested XML document and put it into a 2D array.
Upon making the Get request
https://api.example.com/v1.svc/users?apikey=MY-KEY&source=MY-APP&limit=1000
An XML is produced for each user looking like
<User>
<Id>Rdh9Rsi3k4U1</Id>
<UserName>firstlast#email.com</UserName>
<FirstName>First</FirstName>
<LastName>Last</LastName>
<Active>true</Active>
<Email>firstlast#email.com</Email>
<AccessLevel>Learner</AccessLevel>
</User>
Each user has a similar looking output stacked on top of each other. How could this be scrubbed into an array? Example, the first array would have 7 "columns" with all shown information with each user having a row.
b
So I figured it out for anyone looking for an answer to this type of question in the future. Basically, I found out that the API I was trying to reach (not actually "citrowske.com" as shown in the example) did not allow for CORS or jsonp which left me with the only option of using a Proxy.
Shown is an example of code similar to what I ended up using (below), along with the test XML file shown here
A basic explanation of how this works, it uses the proxy to get the XML file and stores it as "xml" found as "function(xml)". Then the XML doc is searched and each section that starts with "User" gets the "FirstName" and "LastName" data pulled from it and appended to dropdown in the HTML section named "yourdropdownbox".
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'http://citrowske.com/xml.xml',
function (xml) {
//console.log("> ", xml);
//$("#viewer").html(xml);
////////////////////////////////////
var select = $('#yourdropdownbox');
select.append('<option value="">Select a User</option>');
$(xml).find('User').each(function(){
var FirstNames = $(this).find('FirstName').text();
var LastNames = $(this).find('LastName').text();
select.append("<option value='"+ FirstNames +"'>"+FirstNames+" "+LastNames+"</option>");
});
}
////////////////////////////////////
);
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select id="yourdropdownbox">
</select>
As a note, Proxy's are not known for being extremely secure, so watch out what you use this for.
Also, if I wanted to turn the data into an array instead of appending it each time I could have added
var firstnamesarray = ["0"];
var lastnamesarry = ["0"];
var i = 0;
Above the top row of forward-slashes and then replaced:
var FirstNames = $(this).find('FirstName').text();
var LastNames = $(this).find('LastName').text();
with
firstnamesarry[i] = $(this).find('FirstName').text();
lastnamesarry[i] = $(this).find('LastName').text();
i = i+1;
and replaced the "select.append" First & Last Names with
firstnamearry[i] & lastnamearry[i]
To view a working example, check out the jsfiddle here

Get JSON data from external URL and insert in a div as plain text

I have written a function to display some paragraph tags from an external webpage. For some reason the results are displayed in firebug console but not showing on the web page as I wanted (blank page).
function requestCrossDomain(callback){
var querylink = "select * from html where url='http://somedomain.com'" +
" and xpath='/html/body/div/div/div[2]/div/div/div/dl'";
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent(querylink) + '&format=json&callback?';
$.getJSON(yql, function(data){
if (typeof callback === 'function'){
callback(data);
}
});
}
My firebug console shows the below value.
{"query":{"count":1,"created":"2013-12-23T06:31:46Z","lang":"en-US","results":{"dd":{"p":"Hills: High"}}}}
How can I modify the code to display the value of the P tag, which is "Hills: High"
I'm calling the function from HTML code and trying to display the value inside "#targetWrapper"
requestCrossDomain(function(results){
$('#targetWrapper').html(results);
});
Edited to reflect a functional fiddle
$(document).ready(function(){
requestCrossDomain();
});
function requestCrossDomain(){
var querylink = "select * from html where url='http://www.bom.gov.au/wa/forecasts" +
"/armadale.shtml' and xpath='/html/body/div/div/div[2]/div/div" +
"/div/dl'";
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent(querylink) + '&format=json&callback?';
$.getJSON(yql, function(data){
$('#targetWrapper').html(data.query.results.dl.dd[0].p);
$("#targetWrapper").append("<br/><strong>" + JSON.stringify(data) + "</strong>");
});
}
Your data format was very much off the mark AND you cannot have two functions with the same name.
The object you get back from $.getJSON is a simple Javascript Object. You can access it just as you would any other object:
In this case, you'd use:
requestCrossDomain(function(results) {
$("#targetWrapper").html(results.query.results.dd.p);
}
I would highly recommend that you read the MDN documentation I linked above. Having MDN bookmarked is also a good idea; it's a great resource to have easy access to.

Categories