An RSS Reader is used to read RSS Feeds.
AJAX RSS Reader
In this example we will demonstrate an RSS reader, where the content from the RSS is loaded into a webpage without refreshing.
Example Explained – The HTML page
The HTML page contains a link to an external JavaScript, an HTML form, and a div element:
| <html> <head> <script type="text/javascript" src="getrss.js"></script> </head> <body> <form> <p><div id="rssOutput"> |
The HTML form works like this:
- An event is triggered when a user selects an option in the drop-down box
- When the event is triggered, the function showRSS() is executed
- The <div id="rssOutput"> is a placeholder for the data returned from the showRSS() function
Example Explained – The JavaScript code
This is the JavaScript code stored in the file "getrss.js":
| var xmlhttp;
function showRSS(str) function stateChanged() function GetXmlHttpObject() |
The stateChanged() and GetXmlHttpObject functions are the same as in the PHP AJAX Suggest chapter.
The showRSS() Function
Every time an option is selected in the input field, this function executes the following:
- Calls the GetXmlHttpObject() function to create an XMLHTTP object
- Defines the URL (filename) to send to the server
- Adds a parameter (q) to the URL with the selected option from the drop-down list
- Adds a random number to prevent the server from using a cached file
- Each time the readyState property changes, the stateChanged() function will be executed
- Opens the XMLHTTP object with the given URL
- Sends an HTTP request to the server
Example Explained – The PHP page
The PHP page called by the JavaScript code is called "getrss.php":
| <?php //get the q parameter from URL $q=$_GET["q"]; //find out which feed was selected $xmlDoc = new DOMDocument(); //get elements from "<channel>" //output elements from "<channel>" //get and output "<item>" elements echo ("<p><a href=’" . $item_link |
When an option is sent from the JavaScript, the following happens:
- PHP finds out which RSS feed was selected
- An XML DOM object is created for the selected RSS feed
- The elements from the RSS channel are found and outputted
- Loops through the first three elements and output result
