How to reed rss feeds with jquery mobile - javascript

I tried to read an RSS feed from an external website with the following code:
$.get('http://myrssurl.com',function (XMLmediaArray) {
$(XMLmediaArray).find('item').each(function() {
var item = $(this);
var title = item.find('title').text();
var description = item.find('description').text();
var link = item.find('link').text();
var image = item.find('enclosure[type="image/jpeg"]').attr('url');
});
});
I got an error message which says:
XMLHttpRequest cannot load http://myrssurl.com. No '*Access-Control-Allow-Origin*' header is present on the requested resource. Origin 'localhost is therefore not allowed access.
Do you know how to solve this?
Thanks for your help! in the meanwhile I tried to use the GOOGLE RSS FEED service but I also have to deal with a problem by using this:
in the html file I'm using this:
<script type="text/javascript">
new rssdisplayer("msndiv","http://www.myrssfeedurl",6,"date, description");
</script>
and in the Javascript file the follow:
google.load("feeds", "1"); //Load Google Ajax Feed API (version 1)
function rssdisplayer(divid, url, feedlimit, showoptions){
this.showoptions=showoptions || "" //get string of options to show ("date" and/or "description"wink
var feedpointer=new google.feeds.Feed(url) //create new instance of Google Ajax Feed API
feedpointer.setNumEntries(feedlimit) //set number of items to display
document.write('<div id="'+divid+'">Loading feed, </div>')
this.feedcontainer=document.getElementById(divid)
var displayer=this
feedpointer.load(function(r){displayer.formatoutput(r)}) //call Feed.load() to retrieve and output RSS feed
}
rssdisplayer.prototype.formatdate=function(datestr){
var itemdate=new Date(datestr)
return "<span style='color:gray; font-size: 90%'>"+itemdate.toLocaleString()+"</span>"
}
rssdisplayer.prototype.formatoutput=function(result){
if (!result.error){ //if RSS feed successfully fetched
var thefeeds=result.feed.entries //get all feed entries as a JSON array
var rssoutput="<ul>"
for (var i=0; i<thefeeds.length; i++){ //loop through entries
var itemtitle="" + thefeeds[i].title + ""
var itemdate=/date/i.test(this.showoptions)? this.formatdate(thefeeds[i].publishedDate) : ""
var itemdescription=/description/i.test(this.showoptions)? "<br />"+thefeeds[i].content : ""
rssoutput+="<li>" + itemtitle + " " + itemdate + itemdescription + "</li>"
}
rssoutput+="</ul>"
this.feedcontainer.innerHTML=rssoutput
}
else //else, output error
alert("Error fetching feeds: "+result.error.message)
}
but when I execute it in the Browser I get this error message:
Uncaught ReferenceError: rssdisplayer is not defined (index):127 (anonymous function)
Do you guys know what the issue is?

This is an AJAX security: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
You are not allowed to query on other websites.
I would recommend to parse the RSS feed on your server and re-format it in JSON for convenience.

I solved it with the Google API RSS Feed Service. The error came because the rssdisplayer.js file was included too late in the html file. Include it directly after the jquery mobile javascript

Related

Fetching data from spreadsheet in script: "Data table is not defined"

I’m trying to make a script using the Google Visualization App Geomap. In the example code on the Google Developers page, they are using a hard coded table. What I want to do, is to make code use data from a Google Spreadsheet connected to a Google Form. More specifically, I want to use the data of the spreadsheet tab «countries» from the following spreadsheet: https://docs.google.com/spreadsheets/d/1l77TXctG6mgva1ggs3iR3eBNx949hzn9SiVjki1v59I/edit?usp=sharing.
Somehow this does not work, and I get the error messages listed below.
How can I collect the data from the spreadsheet in the right format? I have attempted to use this procedure to collect the data from the spreadsheet: https://google-developers.appspot.com/chart/interactive/docs/spreadsheets.
Error message on web page:
"Data table is not defined"
Error message in Safari Console:
TypeError: undefined is not an object (evaluating 'new google.visualization.Query’)
drawChart help:113
(anonymous function) help:117
My code
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["geomap"]});
google.setOnLoadCallback(drawMap);
function drawMap() {
var opts = {sendMethod: 'auto'};
// ***My code***
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1l77TXctG6mgva1ggs3iR3eBNx949hzn9SiVjki1v59I/edit#gid=957991050', 'sheet=countries', 'headers=1');
var data = query.send(handleQueryResponse);
var options = {};
options['dataMode'] = 'regions';
var container = document.getElementById('regions_div');
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
};
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
return response.getDataTable();
}
</script>
Hope there is someone out there who can help me with this (hopefully) not so hard task. Thank you very much in advance! :-)
You can get data inside of a callback function handleQueryResponse
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
} else {
var container = document.getElementById('regions_div');
var geomap = new google.visualization.GeoMap(container);
var data = response.getDataTable();
geomap.draw(data, options);
}
}
Google provides example here.
Also check format which you get in response and use method google.visualization.arrayToDataTable to format data as in example if needed cause it format should be correct.

Yahoo weather rss feed parsing error

I am trying to parse Yahoo weather RSS feed using jquery.
I am using this code from How to parse an RSS feed using JavaScript?
$.get('http://weather.yahooapis.com/forecastrss?w=2502265', function(data) {
$(data).find("channel").each(function() {
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("description: " + el.find("description").text());
});
});
Now in Firebug console this line is shown in red
GET http://weather.yahooapis.com/forecastrss?w=2502265 200 OK 1.84s
and if i expand this i am getting an error under xml tab
XML Parsing Error: no element found Location: moz-nullprincipal:{b89cceaa-43a2-4015-b9cf-578d1ce6afee} Line Number 1, Column 1:
How can i fix this ?

Retrieve XML Data to use webpage

What I am trying to do:
Get location based off of IP (Done)
Use the City and Country code to use openweather's API (Done)
Read the XML into my webpage so that I can display the "Temperature" field.
This is my first venture into using XML in webpages, and I've tried for 3 days now with no success. I have searched google and stackoverflow, and have tried many things so far, including SimpleXMLElement, with no luck.
What I currently have on my page is just a generated link to the XML sheet for your location.
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
var country = geoip_country_code();
var city = geoip_city();
document.write('Link text');
</script>
How am I able to display the text from the required field on my page?
Thanks in advance! :)
It might be easier to change the API call to return JSON, in which case you could then use this code, the temps are stored in temp, temp_min and temp_max.
var country = geoip_country_code();
var city = geoip_city();
$.getJSON('http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=json&units=metric', function( json ) {
var temp = json.main.temp;
var temp_min = json.main.temp_min;
var temp_max = json.main.temp_max;
document.write( 'Temp: ' + temp + '<br>');
document.write( 'Temp Min: ' + temp_min + '<br>');
document.write( 'Temp Max: ' + temp_max + '<br>');
});
You could use javascript library to convert the xml into a javascript object - one such library is called xml2json, it works as a jQuery plugin: http://www.fyneworks.com/jquery/xml-to-json/
Then you can simply do:
var xmlObject;
$.ajax({
url: url_of_xml,
success: function(data) {
xmlObject = $.xml2json(data);
}
});
Then you just need to place the data on your page. The object in my example is faked, but it gives you the idea:
// put this line in the success callback of your ajax call
// after you create the xmlObject
$('#temp').html(xmlObject.weather.temp);
To display the temperature you get the XML, and read one of the three temperature attributes from the XML returned:
$.get("http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=xml&units=metric", function(xml) {
avg = $(xml).find("temperature").attr("value"));
max = $(xml).find("temperature").attr("max"));
min = $(xml).find("temperature").attr("min"));
(using JQuery)

AJAX parse + Yahoo YQL returning no results?

I'm working on a script that gets all the <table> elements from an external website by going through Yahoo's YQL. This has worked fine recently, but it stopped working as of today. I'm not entirely sure why, all websites used to work with this code:
<script type="text/javascript">
$(document).ready(function () {
var container = $('#target');
function doAjax(url) {
if (url.match('^http')) {
$.getJSON("http://query.yahooapis.com/v1/public/yql?"
+ "q=select%20*%20from%20html%20where%20url%3D%22"
+ encodeURIComponent(url)
+ "%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var fullResponse = $(filterData(data.results[0])),
justTable = fullResponse.find("body");
container.append(justTable);
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
});
} else {
$('#target').load(url);
}
}
function filterData(data) {
data = data.replace(/<?\/body[^>]*>/g, '');
data = data.replace(/[\r|\n]+/g, '');
data = data.replace(/<--[\S\s]*?-->/g, '');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
data = data.replace(/<script.*\/>/, '');
data = data.replace(/<img[^>]*>/g, '');
return data;
}
doAjax('http://www.google.com');
});
</script>
I changed the url to google and changed it to find the <body> tag instead of <table> tags to better show its not working. I looked at the URL that it's requesting and it's not showing any content. Not sure what the problem is though.
Have you checked if the "external website" you have crawled has structural changes?
When it has worked before and now not anymore, then my tip is that the site structure has changed.
It looks like the problem was that YQL was down? I just tested it again and it worked out fine. I wish they would tell us in the future if an outage occurred.

jquery, json and xml

I have a database at zoho creator. They feed me a json of the database content. I have trouble to parse and display that data with jquery or php or in html
Question : So how do I capture json data, and save (convert) it to file as XML. With the xml file I can parse it with jquery xpath easily... the "file" will be a local database, as a backup (if saved)
anybod have clue on that ?
as request.. here is the link for the query -link-
getting a way to display data from var i need is the minimum i must have !
like prod_categorie or prod_nom
note :
i can get help with any tutorial on
how to get xml data from zoho
any json to xml converter (jquery)
out there ?????
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div id="Liste_output"></div>
<script type="text/javascript">
jQuery.ajax({
url: "http://creatorexport.zoho.com/marcandremenard/application-lemieux/json/Liste_produits_View1/7GWhjVxYeNDePjPZnExCKy58Aqr21JX2hJEE6fAfgfkapEQnRjRd5RUy8wdjKuhmFEhJR9QRsBCUBjACAdSgmJNQSvxMt6geaMNC/",
dataType: "json",
success: function(data) {
var Liste_div = jQuery("#Liste_output");
var Liste_data = data["Liste_des_produits1"];
for (var i=0; i<Liste_data.length; ++i) {
var prod_i = Liste_data[i];
Liste_div.append('<div>' +
'<div>Nom: <span>' + prod_i["prod_nom"] + '</span></div>' +
'<img src="/images/prod/'+ prod_i["prod_photo"] +'"/>' +
'<div>Description: <span>' + prod_i["prod_desc"] + '</span></div>' +
'<div>Ingredient: <span>' + prod_i["prod_ingredient"] + '</span></div>' +
'<div>Odeur: <div class="odeur_cls"></div></div>' +
'<div>Certification: <div class="cert_cls"></div></div>' +
'</div>');
var odeur_data = prod_i["prod_odeur"];
for (var j=0; j<odeur_data.length; ++j) {
jQuery('#Liste_output odeur_cls').eq(j).append('<span>' +
odeur_data[j] + '</span>' + (j<odeur_data.length-1 ? ', ' : ''));
}
var cert_data = prod_i["prod_certification"];
for (var k=0; k<cert_data.length; ++k) {
jQuery('#Liste_output cert_cls').eq(k).append('<div>' + cert_data[k] + '</div>');
}
}
}
});
</script>
</body>
</html>
This will not work from a local file. The HTML must be served from the same domain as the database query, that is, it must be served from http://creatorexport.zoho.com (you can put it in the app subfolder)
– OR –
You must read the zoho docs and find out how to do a "callback" (sometimes called "JSONP"). Usually this is done by adding something like ?callback=data to the end of the URL.
Firstly, Javascript has no file-output capability. The best it can do is send data back to a server for processing there -- so the "capture json data, and save it to file as XML" idea is out.
What problems in particular are you having with using JSON? As it gets converted to a native Javascript object, I find it quite easy to work with myself. Though, I can see that if you wanted to use XPath to query it, JSON is no help. You should still be able to get to whatever data you need, but it might be a bit more verbose.
In your example JSON:
{"Liste_des_produits1":[{"Added_Time":"28-Sep-2009 16:35:03",
"prod_ingredient":"sgsdgds","prod_danger":["sans danger pour xyz"],"prod_odeur"..
You could access the prod_danger property like this:
$.getJSON(url, function(data) {
var danger = data.List_des_produits1[0].prod_danger;
});
If you are having trouble getting the right path to a property, Firebug is a great help with this. Just call this:
$.getJSON(url, function(data) {
console.log(data);
});
...and then you can browse through its properties in a tree-structure.
There are jQuery pluggins for such convertion, for example json2xml.

Categories