Yahoo weather rss feed parsing error - javascript

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 ?

Related

Script does not work from shell but works from remote debugger

I am trying to automate a bugzillametrics query. From a browser, If I do
http://10.x.x.x:8080/BugzillaMetrics1_3/#calculate_query,1.1.1, the query works fine and i can get the relevant graph from bugzillametrics. In order to automate this progress, I am using phantomjs. My phantomjs script is as follows:
var webPage = require('webpage');
var page = webPage.create();
var postBody1 = '';
page.open('http://10.x.x.x:8080/BugzillaMetrics1_3/#calculate_query,1.1.1 ',function(status) {
console.log('Status: ' + status);
var content = page.content;
console.log('Content: ' + content);
page.onError = function (msg, trace) {
console.log(msg);
trace.forEach(function(item) {
console.log(' ', item.file, ':', item.line);
});
};
phantom.exit();
});
If I run the script using "./phantomjs post1.js", the bugzillametrics does not create the necessary output. In fact, all i get is status = success. However, If I open the remote debugger and execute the same script using "__run()", I get correct results. What should I do different from the shell ?

How to reed rss feeds with jquery mobile

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

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)

Form fill and capture fail sometimes using CasperJS

I want to fill the form and take capture of the generated page. So I wrote a CasperJS (This is my first time to use CasperJS) to archive to goal. I read the CasperJS API document but still not sure how to fix the problem.
Below is my code:
var casper = require('casper').create();
var filename = casper.cli.get(0);
var myear = casper.cli.get(1);
var mmon = casper.cli.get(2);
var stk_no = casper.cli.get(3);
casper.start('http://www.twse.com.tw/en/trading/exchange/STOCK_DAY/STOCK_DAYMAIN.php', function() {
this.fill("form[name='date_form']", {
'myear' : myear,
'mmon' : mmon,
'STK_NO': stk_no
},true);
});
casper.then(function() {
this.capture(filename);
this.echo("Saved screenshot of " + (this.getCurrentUrl()) + " to " + filename);
});
casper.run();
My command is like
casperjs test.js picture.png 2013 12 8271
Sometimes no picture file will be generated and it turns out to be failed:
Saved screenshot of http://www.twse.com.tw/en/trading/exchange/STOCK_DAY/STOCK_DAY.php to picture.png
Sometimes a picture file will be generated and it turns out to be successful:
Saved screenshot of http://www.twse.com.tw/en/trading/exchange/STOCK_DAY/genpage/Report201312/201312_F3_1_8_8271.php?STK_NO=8271&myear=2013&mmon=12 to picture.png
Why does sometime it work and give the capture but sometimes fail? Why the return value of this.getCurrentUrl() could differ?
When the current URL is http://www.twse.com.tw/en/trading/exchange/STOCK_DAY/STOCK_DAY.php, means you are blocked in the start page and waiting for the redirect, Change your
casper.then(function() {
this.capture(filename);
this.echo("Saved screenshot of " + (this.getCurrentUrl()) + " to " + filename);
});
to:
casper.waitForUrl(/Report/, function() {
this.capture(filename);
this.echo("Saved screenshot of " + (this.getCurrentUrl()) + " to " + filename);
});
/Report/ means "Report" in your current URL, so your are at the page data queried.

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