Imagine using a simple HTML file to send a request to a server script, receive a custom XML file based on the request, and display it to the user without refreshing the browser! The author will discuss with you how to combine PHP and AJAX technologies in common Web applications to create real-time data transmission without refreshing the browser.
Although the PHP language is used in this article, please remember that any server language will work normally. To understand this article, I assume that you basically understand JavaScript, PHP, or a similar server-side language.
In this example, AJAX is used to send a request from an RSS feed to a custom PHP Object. This PHP Object copies the feed on the local server and returns this path. The request object receives the path, analyzes it, and displays the data to the user in HTML format. This sounds like it involves many steps. In fact, it consists of only four small files. Four small files are used to balance their specific strengths and make the processing of the entire system efficient.
I think some readers may ask why you want to create a copy of the feed on the local server instead of simply analyzing the original feed. This allows you to bypass the cross-origin restrictions imposed by xml http Request objects. Later, I will explain how to create this custom PHP Object. But first, let's start with form creation.
Create a Request Form
The first thing you need to do is include JavaScript and any CSS files that you may want to use between your HTML head tags. I included a style table to implement the final layout of the aggregator and used a JavaScript file to send requests and analyze the feeds:
<Link href = "css/layout.css" rel = "stylesheet" type = "text/css"/>
<Script src = "js/request. js"> </script>
Next, create a form that sends a request to an RSS feed you selected. The Form I created contains only one input field and one button for submitting the request. The query of this request is a string consisting of the feed input value and a password that will be verified on the server side. As an example, I use the following form:
"Password = mypassword
This code sends a request each time the page is loaded. Therefore, if the page is refreshed, the existing feed string in this input field will be requested during page loading. The following is an example of form data, along with some div labels used to display specific nodes of the analyzed feed:
Copy codeThe Code is as follows: <body onload = "javascript: makeRequest ('request. php? Request = '+ document. feedForm. feed. value + 'password = mypassword'); ">
<Form name = "feedForm" method = "post" action = "javascript: makeRequest ('request. php? Request = '+ document. feedForm. feed. value + 'password = mypassword'); ">
Enter a feed: <input type = "text" name = "feed" id = "feed" size = "20">
<Input type = "submit" name = "submit" value = "Add Feed">
</Form>
<Div id = "logo"> </div>
<Hr/>
<Div id = "copy"> </div>
<Div id = "details"> </div>
</Body>
The three div labels I created are logo, copy, and details. Each of them has an associated style in the layout style sheet. They will be used when we analyze the feeds, but we need to first be able to access the feeds we requested. This can be done using the PHP Object I mentioned earlier.
Create a custom PHP Object
I used PHP to create a small RSS class, which creates a copy of the Request feed on the local server so that it can be accessed by the XML HTTP Request object we will create later. Typically, you cannot request a file across domains, which means that the file to be requested must be on the local server. This class is a way to solve cross-domain problems, because it creates a copy of the feed, this copy is requested on the local server and returns the local path to the feed, then it is accessed by the Request object.
The only method in this class is a request method, which has only one parameter pointing to the requested RSS feed URL. Then, it checks whether a directory is located on the local server through the rss name. If it does not exist, create a directory and set its permission mode to 0666, which means the directory can be read and written. When it is set to readable, the directory can be accessed later. When it is set to writable, you can write a copy of the feed to the directory on the local server:Copy codeThe Code is as follows: // create a directory if it does not exist
$ Dir = "rss ";
If (! Is_dir ($ dir ))
{
Mkdir ($ dir, 0666 );
}
Note:
On a Windows Server, pattern settings in PHP 4.2.0 and later are not required. However, if it exists, it will be ignored; therefore, I keep it for the project to be migrated to a UNIX or Linux server.
Before copying a feed to this server, we need a unique file name. I used the md5 encryption method for this complete URL to ensure that all the feed names are unique. With this new file name, it can connect a string describing the directory pointing to the file; this will be used when creating a copy of the feed:Copy codeThe Code is as follows: // create a unique name
$ File = md5 ($ rss_url );
$ Path = "$ dir/$ file. xml ";
You can create a copy of the file by referring to the defined path above and the original requested feed URL. Finally, return the path to the new file as a response to the request:Copy codeThe Code is as follows: // copy the feed to the local server
Copy ($ rss_url, "$ path ");
Return $ path;
Following is the small, yet powerful RSS class in its entirety:
<? Php
Class RSS
{
Function get ($ rss_url)
{
If ($ rss_url! = "")
{
// Create a directory if the directory does not exist
$ Dir = "rss ";
If (! Is_dir ($ dir ))
{
Mkdir ($ dir, 0666 );
}
// Create a unique name
$ File = md5 ($ rss_url );
$ Path = "$ dir/$ file. xml ";
// Copy the feed to the local server
Copy ($ rss_url, "$ path ");
Return $ path;
}
}
}
?>
To access methods in this PHP class, a request file is required to act as an interface of this class, which is exactly the file we are requesting. This file first verifies a password variable queried from this request, or returns a message indicating that the requester is not an authorized user, you can also use the path pointing to the RSS feed (which is copied to the local server after being processed by the Request Method) to respond. In response to this RSS feed, you need to include this RSS object and instantiate it. You need to use the requested URL as a parameter to activate the request method:Copy codeThe Code is as follows: <?
If ($ password = "mypassword ")
{
Require_once ('classes/RSS. class. php ');
$ Rss = new RSS ();
Echo $ rss-> get ($ request );
}
Else
{
Echo "You are an unauthorized user ";
}
?>
Combination of GET/POST and AJAX
For POST requests, we first need to create the request object. If you have no experience in creating request objects, you can read my article "How To Use AJAX" or simply study the sample source code in this article. Once this request object is created, you can call the sendFeed method and pass the URL created by the form:Copy codeThe Code is as follows: function sendFeed (url ){
Post. onreadystatechange = sendRequest;
Post. open ("POST", url, true );
Post. send (url );
}
Once a response from a PHP Object is received and loaded correctly, another request is sent to the local file corresponding to the response. In this case, post. responseText provides the path to the new file:
Function sendRequest (){
If (checkReadyState (post )){
Request = createRequestObject ();
Request. onreadystatechange = onResponse;
Request. open ("GET", post. responseText, true );
Request. send (null );
}
}
Analysis Response
Because of the differences between RSS feeds, analysis and response are challenging. Some images contain titles and description nodes, while others do not. Therefore, when analyzing feedback, we need to check whether it includes an image. If it includes an image, we can display the image in the image div label together with the title and link of the feed:Copy codeThe Code is as follows: var _ logo = "";
Var _ title = response. getElementsByTagName ('title') [0]. firstChild. data;
Var _ link = response. getElementsByTagName ('link') [0]. firstChild. data ;;
_ Logo + = "<a href = '" + _ link + "'target =' _ blank '>" + _ title + "</a> <br/> ";
If (checkForTag (response. getElementsByTagName ('image') [0])
{
Var _ url = response. getElementsByTagName ('url') [0]. firstChild. data;
_ Logo + = " <br/>"
}
Document. getElementById ('logo '). innerHTML = _ logo;
We must not only check each image to display it, but also check it when traversing all the items in the feed. Because if an image exists, all other titles and link node indexes will not work properly. Therefore, when an image tag is found, we should adjust the index of the title and link node by adding the index value (+ 1) in each traversal:Copy codeThe Code is as follows: if (checkForTag (response. getElementsByTagName ('image') [0]) "" I> 0 ){
Var _ title = response. getElementsByTagName ('title') [I + 1]. firstChild. data;
Var _ link = response. getElementsByTagName ('link') [I + 1]. firstChild. data;
}
Else {
Var _ title = response. getElementsByTagName ('title') [I]. firstChild. data;
Var _ link = response. getElementsByTagName ('link') [I]. firstChild. data;
}
You can use the checkForTag method to check whether a specific tag exists:
Function checkForTag (tag ){
If (tag! = Undefined ){
Return true;
}
Else {
Return false;
}
}
There are many possibilities for feed analysis. For example, you can assign an item to a category that can be folded, so that users can select the content they want to watch. As an example, I use date to classify items-this can be achieved by translating whether the pubDate for a specific item is different from the pubDate of the previous item and displaying a new date accordingly:Copy codeThe Code is as follows: if (I> 1 ){
Var previousPubDate = response. getElementsByTagName ('pubdat') [I-1]. firstChild. data;
}
If (pubDate! = PreviousPubDate | previousPubDate = undefined ){
_ Copy + = "<div id = 'detail'>" + pubDate + "</div> }
_ Copy + = "<a href = \" javascript: showDetails ('"+ I + "'); \ ">" + _ title + "</a> <br/> ";
Document. getElementById ('copy'). innerHTML + = _ copy;
Note that the last part is the showDetails method, which is used to display details when a user selects a specific item from a feed. This method has a parameter (item index value), which is used to find the index of the details node in the feed:Copy codeThe Code is as follows: function showDetails (index ){
Document. getElementById ('details'). innerHTML = response. getElementsByTagName ('description') [index]. firstChild. data;
}
Conclusion
Use AJAX to send a query string to a server script and retrieve a custom response based on the string. This is possible for any web developer. In this way, your next web application will be filled with new possibilities.