I want to recover an RSS feed in JS.
I looked-up on the web a whole day, and found that nearly everybody use google feed API, Yahoo API, or a nodejs/php page for the computing and Jsonification. And I don't want to depend on a service like Google Feed API.
My goal is to fetch an RSS feed, and then create an array where each article on the feed will be an object, in full javascript.
I'm using Angular JS, so if the help could use the benefits of this lib, it would be great, but I'm not closed to any vanilla-JS code if needed.
For those who may want to ask why : it is for a Firefox OS appliaction, and that's why I can't have any php/nodejs. All have to be made in JS.
Thanks,
Tom
What is the problem to make fetching of xml structure directly?
I think using systemXHR permission regular AJAX request should work fine for you.
Then you'll be able to get from xml what you need in apy possible way.
So my best guess would to just use normal DOM parser, and then query the document:
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(txt, "text/xml");
I think nowadays you can also use things like querySelectorAll to quickly iterate over the document, similar to normal DOM. E.g. something like this would work:
[].forEach.call(xmlDoc.querySelectorAll('item'), function(item) {
console.log(item.querySelector('title').textContent);
});
The short answer is that you can't fetch and parse XML feeds on the client without using a 3rd party service because of browser's Same Origin Policies.
From there, there are 2 options:
fetch and parser on the server side. You'll have to do all the grunt work by your self, but then you can easily load the data from the browser, because it will be under the same domain and hence the Same Origin Policy won't apply
compromise on your requirement to not use a 3rd party and use one that transforms the XML feeds into JSON to circumvent the SOP.
In both cases, I suggest you check Superfeedr (which I created!), which I believe can help a lot... we also have an Angular module for feeds.
Thanks for pople who took the time to answer me :)
It appears it is not really possible without any server computing.
I have to confess that I'm pretty lucky, because the service I wanted to call have just realesed a new API, so happy end for me :)
Thanks every body !
Related
Recently I've been working with leaflets, and I'm currently looking at several plugins.
Several of the plugins I've seen (including Leaflet.markercluster) use json to plot points, but instead of using the actual stream, or a json file, the programmer includes a javascript .js file where a variable is set with the json stream. So the js file with the json data looks like this:
var data = [
{"loc":[41.575330,13.102411], "title":"aquamarine"},
{"loc":[41.575730,13.002411], "title":"black"},
{"loc":[41.807149,13.162994], "title":"blue"},
{"loc":[41.507149,13.172994], "title":"chocolate"}
]
I've been working with other type of javascript charts, and most of them read and process a json stream.
It seems these plugins will not work if I create a service that returns json.
Why not use json instead of including a js file that sets a variable with a json stream?
I'm not a javascript expert, but I find it easier to generate json than a javascript file with json in it.
You are wrong about concepts.
1st. JavaScript as a language has its own syntax, so, if you have a function that receive a JSON object as a parameter and you pass it a Number or a String, it'll will throw an Error when you try to access some property. For Ex.
function myjson (obj) {
console.log(obj.prop)
}
myjson(34); //wrong
myjson("{prop: 123}") //wrong
myjson({prop: 123}) //Good, will print 123
Now, imagine that you have some scripts, many .js files that you have indexed in your HTML file, like
<script src="/mycode.js"> </script>
<script src="/myapp.js"> </script>
And you want to add some data, like the one you show for the plot points; then you have to include it in two ways, putting that in a .js file or getting it from a service with an AJAX call.
If you add that in a .js file, you'll have access to them directly from your code, like this
var data = [
{"loc":[41.575330,13.102411], "title":"aquamarine"},
{"loc":[41.575730,13.002411], "title":"black"},
{"loc":[41.807149,13.162994], "title":"blue"},
{"loc":[41.507149,13.172994], "title":"chocolate"}
]
console.log(data)
and if you put that in a .json file file this
/mydata.json
[
{"loc":[41.575330,13.102411], "title":"aquamarine"},
{"loc":[41.575730,13.002411], "title":"black"},
{"loc":[41.807149,13.162994], "title":"blue"},
{"loc":[41.507149,13.172994], "title":"chocolate"}
]
you'll have to fetch and parse the data yourself
fetch("/mydata.json").then(async data => {
var myjson = await data.text();
myjson = JSON.parse(myjson);
console.log(myjson) //A Javascript object
console.log(myjson[1]) //The first element
})
I like #FernandoCarvajal's answer, but I would add more context to it:
JSON is more recent than JS (you could see JSON as a "spin-off" of JS, even though it is now used in combination with much more languages than just JS).
Before JSON was widespread, the main and easiest way to load external data in Browsers was the technique you saw in the plugins demo: assign data into a global variable, which you can use in the next script. Browsers happily execute JS even from cross domain (unless you explicitly specify a Content Security Policy). The only drawback is that you have to agree on a global variable name beforehand. But for static sites (like GitHub pages in the case of the plugins demo you mention), it is easy for the developer(s) to agree on such a convention.
At this stage, you should understand that using this simple technique already fits the job for the sake of the plugins static demo. It also avoids browsers compatibility issues, aligning with Leaflet wide browsers compatibility.
With the advent of richer clients / Front-End, typically with AJAX, we can get rid of the global variable name agreement issue, but now we may face cross domain difficulty, as pointed out by #Barmar's comment. We also start hitting browsers compatibility hell.
Now that we can load arbitrary data without having to agree on a static name beforehand, we can leverage Back-End served dynamic content to a bigger scale.
To workaround the cross domain issue, and before CORS was widespread, we started using JSONP: the Front-End specifies the agreed (callback) name in its request. But in fact we just fallback to a similar technique as in point 2, mainly adding asynchronicity.
Now that we have CORS, we can more simply use AJAX / fetch techniques, and avoid security issues inherent to JSONP. We also replace the old school XML by the more JS-like JSON.
There is nothing preventing you from replacing the old school technique in point 2 by a more modern JSON consumption. If you want to ensure wide browsers compatibility, make sure to use libraries that take care of it (like jQuery, etc.). And if you need cross domain, make sure to enable CORS.
Firstly, thanks for taking time to view my post. I am working on a project with a few people, and we basically have a webpage, and once you log in, it displays all the data from a mysql database which has 6 tables, 3 of which have data in them. We figured out that in order for us to go about this, we need to transfer data by exporting the data into JSON file(s), then from there load the JSON files into java script so it can communicate with the web server. We were wondering what would be the best way to go about this. One way we found out is to reference the JSON ddata as variables and just list everything out, but several of our files have loads and loads of data. Would there be an easier approach?
This would be the first time we are doing something like this, so we are learning and appreciate your feedback!!
If you're using some kind of AJAX library, you can easily request the .json file from the browser.
For example with jQuery:
$.post("ourJSONFile.json", function( data ) {
..logic to display data..
});
NOTE - The comment about no PHP was not posted while I was writing this. Until I know why there can be no PHP, I'm just going to leave this answer here.
I think you're going at this in the wrong way. There is no need for JSON here, just query your database for the information.
The overview of what you need to do is (in PHP or the language you use to talk with your server) you need to
connect to the database
query database for information (query in your case, more or less means get the information)
do something with the returned information (such as echoing it in PHP so it will go to the user)
Now, it doesn't look like there is much effort place for getting this done, only planning. So, I'll just show you a few links to read up. (Which is also why people has devoted your question, Stackoverflow doesn't like asking question with no effort to research answers)
I'd use php.net for looking up methods, such as the mysqli_query method. This is very useful for learning small but important things about the method, like what it returns when an error occurs.
http://php.net/manual/en/mysqli.query.php
Taking a quick look through this guide, I think it should suffice. Besides syntax and such, some other important points are use MySQLI (when using PHP 5 or higher) and use prepared statements.
http://www.pontikis.net/blog/how-to-use-php-improved-mysqli-extension-and-why-you-should
The use of prepared statements is to protect your queries from injections. w3schools gives a good explanation about this # http://www.w3schools.com/sql/sql_injection.asp
MySQLI is MySQL Improved, it is more secured and supported. MySQL has been deprecated since PHP 5, and php.net pages on a MySql method will actually say this at the very top.
Finally, Andrew mentioned AJAX. AJAX is (for example) a way of doing things that would normally require reloading the page, without reloading the page. There is more to that, and I would recommand looking into it once you get use to the languages you are using.
Note, AJAX does not require libraries to use, it can be done with pure javascript. Libraries simply (as seen around) simplify AJAX a lot.
Is there a way to create xml file only with jquery/javascript ?
Not with browser JavaScript, no. You will need some kind of server to write to the file system for you. You could always build the file in JS and then send it through AJAX for the server to write though.
Use jQuery.parseXML to parse a trivial container string:
var xml = '<?xml version="1.0"?><root/>';
var doc = jQuery.parseXML(xml);
Then you can use normal jQuery DOM manipulation to append nodes to that XML document. Once you need to serialize the final document, you can use the answers to this question.
Your question is more complicated than it would first seem. Let's break it down into two parts:
Can I create a file using javascript?
Can I write XML to that file using jQuery/javascript?
Unfortunately, the answer to the first question is no. You cannot use javascript running in a browser to access the file system. This has security implications and will not be allowed by major browsers.
The answer to the first question makes the second one moot. You can create XML in javascript, but you'll have no place to write it.
If you provide more information about the reason you want to do this, it may be possible to find alternative solutions to your problem.
How about creating it by just using Javascript strings and then using this library?
http://plugins.jquery.com/project/createXMLDocument
You can create a document like this:
var doc = document.implementation.createDocument(namespace,rootnode,doctype);
doc.documentElement.appendChild(somenode);
And then serialize it to a string:
new XMLSerializer().serializeToString(doc);
But it will only be in memory. What else do you want to do with it?
Seeing as I'm learning XML myself, this is perhaps an illegal answer as it contains a possible question.
That said, I'm pretty sure that an XML document can be sent to the browser to display. That can then be explicitly saved by the end-user.
I'm a bit new to javascript. Is there a way to do what I am describing in the title completely client-side and without any external libraries? Or is using jQuery the best/only way to go?
You can import a json file from a server via AJAX and them simply eval it. You don't need a library for that but using one makes it a lot easier. Of course just evaling a json string is not very secure as it can contain arbitrary text so all libraries parse it to see if it's well formed etc.
EDIT:
If you want to learn about AJAX you can start with this tutorial from w3schools. Ajax stands for Asynchronous Javascript And XML and it allows you to send a request to the server without reloading the whole page. In your case you will not be using Xml but JSON. Anyway, the tutorial explains the whole idea.
Yes there is. You can use the "document.write" to add scripts to the DOM at runtime:
in your case:
document.write('<script ...></script>');
Basically you are adding the script tag to the dom that will request the new file.
However there is something else to consider, although the script will be downloaded, you will need to have a variable assignment in it in order to use it in your page:
var x = { //json object };
As far as I can tell, the template feature in XUL doesn't allow you to load JSON data into your listbox/tree/etc. element. -- it only supports XML and RDF. The closest thing I found to an indication that it might someday support JSON, is the comments on this blog post from 2007, saying that there was a bug filed. But the bug in question is marked RESOLVED FIXED and JSON is still not supported. So I guess my options are:
Get the data I need in XML, and display it using templates.
Get the data in JSON, and display it by direct DOM manipulation.
Use one of these third-party templating solutions.
So my question is, am I correct that templates don't support JSON? If not, where is that feature documented? If I am correct, what should I consider when choosing among the above three options?
It turns out that writing your own custom object that implements nsITreeView is a lot simpler than I expected, and makes everything seem nice and fast.
I'm not sure about JSON in XUL templates, however I'd suggest option 2, given the ease with which JSON is used within the browser.
From Firefox 3.5, you can just do
var obj = JSON.parse(xhr.responseText);