Just imagine you have a website homepage and a WordPress blog. Now you want to take the first three blog posts to display on your homepage with a title, a short description and a link to that post. How to do it? Just continue reading this simple RSS feed with AJAX tutorial.
Table of contents
1. Getting RSS (XML) source
The first thing to do is to find the RSS source to feed from.
In this article, I will take the RSS source from my own blog, which can be accessed at: https://anhkarppinen.com/feed/
If you are running a WordPress blog, the feed of your blog can also be found at: http://yourblog.domain/feed/
The structure of the XML file in the RSS URL is rather simple:
There are a lot of text, but don’t worry, because this file follows a certain structure. I already circled some tags from the file so that you can see this XML structure easier.
The most important tags are:
- title, link, pubDate and description
So, “item” marks the blog post object inside “channel“. Inside an item, there are “title“, “link“, “pubDate” and “description” of the post.
“Item” stays inside “channel”. And “title”, “link”, “pubDate”, and “description” stay inside item. As simple as that. Then, the structure inside item repeats itself throughout the file.
And that’s the way we will feed up information into our HTML RSS section with AJAX.
2. Creating an HTML file with a section for RSS
Now we create a simple HTML file with some common tags:
Now let’s place an RSS section into the body tag:
The “err” div is to display errors (if any).
The “timeline” div is the real area that information will go into.
You can have free-style CSS for your RSS section, if you want to see mine, scroll down to the bottom of this post and retrieve it from GitHub.
Source for the external resources:
- Bootstrap CSS CDN: https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
- jQuery CDN: https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
3. Call RSS news feed with AJAX into HTML section
So we have a basic HTML file now. Let’s continue with the AJAX script. Just under jQuery source script, input these:
Now if you refresh the page, you already can get the blog post title, description, published date and link to the webpage.
This line digs into the structure of the XML and takes back the first 3 items.
These lines find the specific tags in the XML and extract content text from them.
This line finds the published date in the file and takes only the first 17 letters (date, month, year), because I don’t want the time to be also displayed.
Notice: If you are in localhost and the RSS source is from another hosting server, you may get the error: “Failed to get feeds.”
4. Demo and download full source code
Demo: RSS feed with AJAX demo
Source code from GitHub: RSS feed with AJAX
Erwin Garret says
Thanks For Sharing
You’re welcome 🙂