Real-time implementation using PHP, XML, and jquery

Source: Internet
Author: User

Quick Start
Abbreviations

  • Ajax: Asynchronous JavaScript + XML
  • CSS: stacked style sheet
  • DOM: Document Object Model
  • HTML: Hypertext Markup Language
  • JSON: JavaScript Object symbol
  • Ui: User Interface
  • URL: Uniform Resource Locator
  • XML: Extensible Markup Language

Google's instant feature is a new search enhancement. as you type the result, it has gained a lot of attention and it is easy to understand why. All you need to do to get the result is to type. You do not need to press enter to view the results, then adjust your search and press enter again. This will all happen with your input. If you have not done so, try again. Surprisingly, such a small change can produce such a big difference in availability.
The main benefit of this kind of real-time functions is the ease of implementation, especially when you are using client tools such as jquery (see references ). In this article, you need to follow the process of building a simple search engine, and then create an Instant Search user interface for the engine.
All of this begins with retrieving search data.

Set Data
For this article, I decided to search for the "Simpson family" series. I create an XML file (including in source code download) that contains all the "Simpsons" series, titles, seasons, sets, playback dates, and summaries of each set ). You can see part of the XML in Listing 1.

Listing 1. XML Data Source

<? XML version = "1.0" encoding = "UTF-8"?>
<Episodes>
<Episode Title = 'sons sons roasting on an open fire' Episode = '1' season = '1'
Aired = '17 December 1989 '>
Christmas seems doomed for the Simpson family when Homer es no
Christmas bonus. Homer becomes a mall Santa Claus, hoping to make money and
Bring Marge, Bart, Lisa, and baby Maggie, a happy holiday.
</Episode>
...
</Episodes>

It is actually a very large file with a size of about 840 K. This should not be surprising, because the "Simpson family" has been playing for 22 years.
The next step is to compile a PHP class that can perform XML parsing and search for you. This class is called Simpsons, as shown in Listing 2.

Listing 2. Simpsons Search Class

<? PHP
Class Simpsons {
Private $ episodes = array ();
Public Function _ construct (){
$ Xmldoc = new domdocument ();
$ Xmldoc-> load ("Simpsons. xml ");
Foreach ($ xmldoc-> documentelement-> childnodes as $ episode)
{
If ($ episode-> nodetype = 1 ){
$ This-> episodes [] = array (
'Episode' => $ episode-> getattribute ('episode '),
'Season '=> $ episode-> getattribute ('season '),
'Title' => $ episode-> getattribute ('title '),
'Aired' => $ episode-> getattribute ('aired '),
'Summary '=> $ episode-> nodevalue );
}
}
}
Public Function find ($ q ){
$ Found = array ();
$ Re = "/". $ Q. "/I ";
Foreach ($ this-> episodes as $ episode ){
If (preg_match ($ re, $ episode ['summary ']) |
Preg_match ($ re, $ episode ['title']) {
$ Found [] = $ episode;
}
}
Return $ found;
}
}
?>

The constructor of this class uses the xml dom library standard for PHP to read the XML file of the drama information. It iterates all the subnodes of the root node and extracts their seasonal numbers, titles, playback dates, and drama attributes, as well as the text of the node that contains the abstract. Then, all the data is appended to the series array as a hash table, which is a member variable.
Then, the find function searches for the Series list to use a simple regular expression that matches the title and abstract to find matching items. Any matching series is appended to an array and then returned to the caller. If the array is empty, no match is found.
Now that you have data, the next step is to build an Ajax Response Program. Your real-time UI will call this response program to retrieve data.

Create an Ajax response page
The UI of the first version uses HTML response for Ajax requests. This method is the simplest way to implement instant UI. The instant UI web page uses the search keyword and the keyword to send Ajax requests to the server. The server then formats the HTML block that constitutes the response and returns it to the page. In a simple call, the code in the instant UI web page replaces Part of the page with updated HTML.
Later in this article, I will demonstrate how to use XML and JSON responses from the server, but now, for simplicity, we start with the html version.
The first thing you need is the HTML response page. This page accepts query strings from the request. Use this string to call the Simpsons class to search for the series. Then, format the returned series array in HTML. This code is located in listing 3.

Listing 3. html Ajax response page

<? PHP
Include 'sons sons. php ';

$ S = new Simpsons ();
$ Episodes = $ S-> Find ($ _ request ['q']);
If (count ($ episodes) = 0 ){
?>
No results found
<? PHP
} Else {
?>
<Table>
<? PHP foreach ($ episodes as $ e) {?>
<Tr> <TD class = "episode"> <B> <? PHP echo ($ E ['title'])
?> </B>-
Season <? PHP echo ($ E ['season '])?>
Episode <? PHP echo ($ E ['episode'])?> -
Aired on <? PHP echo ($ E ['aired'])?> </TD> </tr>
<Tr> <TD class = "summary"> <? PHP echo ($ E ['summary '])
?> </TD> </tr>
<? PHP }?>
</Table>
<? PHP
}
?>

At the top, listing 3 includes the Simpsons class. Then the Code creates a new instance of this class and calls find. Then, it checks whether the response is empty and whether "no results found" is returned. Otherwise, it traverses these results and forms a result table.
To test this page, you only need to go to your web browser and request this page. You can see the output in Figure 1.

Figure 1. html Ajax response page

At this point, you have everything you need to start building the Instant Search UI.

 

Back to Top

Build an instant search UI
Using the Javascript jquery library, you can easily build an instant search UI. View list 4 to understand what I mean.

Listing 4. Real-time pages with HTML responses

<HTML>
<SCRIPT src = "jquery-1.4.2.min.js"> </SCRIPT>
<LINK rel = "stylesheet" href = "styles.css" type = "text/CSS"/>
<Title> instant search-HTML based </title>
</Head>
<Body>
Simpsons search: <input type = "text" id = "term"/>
<Div id = "Results">
</Div>
<SCRIPT>
$ (Document). Ready (function (){
$ ('# Term'). keyup (function (){
$. Get ('search _ html. php? Q = '+ escape ($ (' # term '). Val (), function (data ){
Certificate ('{results'{.html (data );
});
});
});
</SCRIPT>
</Body>
</Html>

At the top of the page, listing 4 includes the jquery library and CSS style sheet to make the output more beautiful. The subject of the page includes the input field for the search keyword and the result Div for saving the output.
Most of the work is done in the Javascript section at the bottom of the page. It first calls the ready function in the document. This call ensures that internal Javascript is not executed before the page is ready. Internal JavaScript uses the keyup function in the search keyword output object to monitor the keyword type in the search keyword field. When a text field is changed, the Ajax get method is called on the server. By using the HTML function, the data response from this call is used to fill in the result element.
It doesn't matter if the JavaScript code looks like line noise. This is actually the technical status of JavaScript. The code needs to be reviewed, so the code size should be smaller.
Although you can do this without a jquery library, the value of using this library is that the code is very concise and all cross-platform work has been done for you. You don't have to worry about Internet Explorer and safari or Firefox; just write the code once and use it anywhere.
To test the library, create an instant search UI in the Web browser. In Figure 2, you can see something similar.

Figure 2. Enter a few letters in the Search Keyword

Figure 2 shows the page after I enter a few characters. After I type the keyword "Frink", you can see the result in figure 3.

Figure 3. After entering a keyword

Figure 3 shows "Frink" in the title or two-set summary ". Funny data! Professor Frink (the best role in the program so far) has been present in more than two sets. But this is still amazing. The response time on the local computer is excellent, even if the server code is parsed through 840 KB of XML.
Now you may want to control the number of requests by placing a delay between each key and when you actually send the request. In listing 5, the updated code can perform this operation.

Listing 5. Using Real-Time pages with delayed HTML responses

<HTML>
<LINK rel = "stylesheet" href = "styles.css" type = "text/CSS">
<SCRIPT src = "jquery-1.4.2.min.js"> </SCRIPT>
<Title> instant search-HTML based with delay </title>
</Head>
<Body>
Simpsons search: <input type = "text" id = "term"/>
<Div id = "Results">
</Div>
<SCRIPT>
Delaytimer = NULL;

Function getresults (){
$. Get ('search _ html. php? Q = '+ escape ($ (' # term '). Val (), function (data ){
Certificate ('{results'{.html (data );
});
Delaytimer = NULL;
}

$ (Document). Ready (function (){
$ ('# Term'). keyup (function (){
If (delaytimer)
Window. cleartimeout (delaytimer );
Delaytimer = Window. setTimeout (getresults, 200 );
});
});
</SCRIPT>
</Body>
</Html>

This Code creates a timer when you press a button. When the timer stops after 200 milliseconds, the request is sent. If another key is set before the timer is stopped, the original timer is canceled and a new timer is created. The result is that after the user stops typing, the timer stops for 200 milliseconds. Although the interface always feels like the original one, the number of requests sent to the server is greatly reduced, especially when users enter the interface quickly.
Although we can do so far, there are actually two other ways to perform this instant process.

Migrate to XML
The first method is to use XML as the transmission syntax from the server to the client. The idea here is that the server provides a common XML endpoint, which can be used by any process to perform queries, and your client is smart enough, you can read XML and format it as needed.
To change to XML, you must first create a new server page as shown in Listing 6.

Listing 6. xml Ajax page

<? PHP
Include 'sons sons. php ';

Header ('content-type: text/xml ');

$ S = new Simpsons ();
$ Doc = new domdocument ();
$ Root = $ doc-> createelement ('episode ');
$ Doc-> appendchild ($ root );
Foreach ($ S-> Find ($ _ request ['q']) as $ episode ){
$ El = $ doc-> createelement ('episode ');
$ El-> setattribute ('title', $ episode ['title']);
$ El-> setattribute ('episode', $ episode ['episode']);
$ El-> setattribute ('season ', $ episode ['season']);
$ El-> setattribute ('aired', $ episode ['aired']);

$ Tn = $ doc-> createtextnode ($ episode ['summary ']);
$ El-> appendchild ($ Tn );

$ Root-> appendchild ($ El );
}
Print $ doc-> savexml ();
?>

Although the search is still the same, the method of formatting the result has changed. Now, the Code creates an XML document and attaches the node to it to save all the returned data. At the end of the script, it only saves the xml dom as a string. Note that at the top of the script, you must set the content type to text/XML when exporting XML instead of HTML.
If you navigate to this page in your web browser, you will see a situation similar to Figure 4.

Figure 4. XML response page

However, some browsers may display the returned text in a more structured manner. If you want to view the original source XML, you can selectView-sourceTo see a window similar to figure 5.

Figure 5. source code of the XML response page

As you can see, this script creates some well-formatted XML, ready for use by new client code.
The new client code for parsing XML (instead of using HTML directly) is located in listing 7.

Listing 7. Using XML for Instant Search

<HTML>
<SCRIPT src = "jquery-1.4.2.min.js"> </SCRIPT>
<LINK rel = "stylesheet" href = "styles.css" type = "text/CSS"/>
<Title> instant search-XML based </title>
</Head>
<Body>
Simpsons search: <input type = "text" id = "term"/>
<Table id = "Results">
</Table>
<SCRIPT>
$ (Document). Ready (function (){
$ ('# Term'). keyup (function (){
$. Get ('search _ xml. php? Q = '+ escape ($ (' # term '). Val (), function (data ){
Html = '<Table id = "Results"> ';
$ (Data). Find ('episode'). Each (function (){
VaR Ep = $ (this );
HTML + = '<tr> <TD class = "episode"> <B>' +
Ep. ATTR ('title') + '</B> & nbsp ;';
HTML + = 'season '+ EP. ATTR ('season') + '& nbsp ;';
HTML + = 'episode' + EP. ATTR ('episode') + '& nbsp ;';
HTML + = 'aired' + EP. ATTR ('aired') + '</TD> </tr> ';
HTML + = '<tr> <TD class = "summary">' +
Ep. Text () + '</TD> </tr> ';
});
HTML + = '$ ('# Results'). replacewith (HTML );
});
});
});
</SCRIPT>
</Body>
</Html>

The client code used to monitor the keys and send Ajax requests is almost the same. The difference is that different URLs get XML data instead of HTML data.
After the data is returned, the Code uses jquery to search for all drama tags. It can then format a large amount of XML and use the replacewith function to replace the old table with the new table. Because jquery is used, this code is easier to use than the native DOM function of the browser.
Another way to transmit data is through JSON (JavaScript Object symbol ).

Migrate to JSON
In the Web 2.0 world, JSON is a very popular mobile data method. It is small, convenient, and fast, making it easy for the browser to read, because all the operations that need to be done are to evaluate the JavaScript code that has been returned. Creating JSON is also simple, as you can see in the JSON version of the Ajax search page in listing 8.

Listing 8. JSON Ajax page

<? PHP
Include 'sons sons. php ';

Header ('content-type: Application/json ');

$ S = new Simpsons ();
Print json_encode ($ S-> Find ($ _ request ['q']);
?>

You only need to use the json_encode function to convert the returned array into JSON code. If you are curious, there is also a json_decode function that can convert JSON back to the basic PHP type. Most popular languages have the same simple JSON mechanism as here, which can convert the basic data structure to JSON or to JSON.
If you view the JSON page in the browser, you will see a response page similar to figure 6.

Figure 6. JSON response page

Although this page may not attract people's attention, this page looks very easy to read for JavaScript interpreters in browsers.
The corresponding real-time UI web code used to read JSON formatted output is located in listing 9.

Listing 9. JSON Instant Search UI

<HTML>
<SCRIPT src = "jquery-1.4.2.min.js"> </SCRIPT>
<LINK rel = "stylesheet" href = "styles.css" type = "text/CSS"/>
<Title> instant search-JSON based </title>
</Head>
<Body>
Simpsons search: <input type = "text" id = "term"/>
<Table id = "Results">
</Table>
<SCRIPT>
$ (Document). Ready (function (){
$ ('# Term'). keyup (function (){
$. Get ('search _ JSON. php? Q = '+ escape ($ (' # term '). Val (), function (data ){
Html = '<Table id = "Results"> ';
$. Each (data, function (IND, EP ){
HTML + = '<tr> <TD class = "episode"> <B>' + EP. Title + '</B> & nbsp;'; s
HTML + = 'season '+ EP. Season +' & nbsp ;';
HTML + = 'episode' + EP. Episode + '& nbsp ;';
HTML + = 'aired' + EP. aired + '</TD> </tr> ';
HTML + = '<tr> <TD class = "summary">' + EP. Summary + '</TD> </tr> ';
});
HTML + = '$ ('# Results'). replacewith (HTML );
});
});
});
</SCRIPT>
</Body>
</Html>

This code is very similar to XML code. The difference is that you can use the jquery each function for the returned array, and then use the dot symbol to access all the important keywords in the data (that is, title, drama series, summary, etc ).
Now you have the initial implementation of the instant search function that can be used as your work start point.

Some Supplements
Compared with what Google developers do, this implementation has three major differences. First, scale. They process billions of searches every day, and now they can process billions of individual small searches with each key. Although there are many problems and solutions in this regard, you have to do at least one thing-browser cache in this case. If you type the same keyword twice, only one request is actually made because of browser cache, because the browser returns the cached data when the second request is sent.
Another thing Google does is prefetch the results. For example, if you type "mov", it indicates that you are looking for "Movies", perform this search, and use the gray text for the "ies" you are missing to indicate this.
The third difference is the support for paging, which is quite easy to solve. All you need to do is add some JavaScript For the page link at the bottom of the page, and then call this script when the user clicks to browse from the first page to any subsequent page.

Conclusion
Google's real-time UI function is really real-time. Is it revolutionary? No. But it is a small step that has a profound impact on availability. As you can see in this article, by using standard tools such as XML, PHP, and jquery, the initial stages of these actions are not difficult to implement.
I hope that you can use the Code provided in this article in your project. If you have done so, please let me know. I'm glad to see how you use it.

This article is transferred from www.35java.com 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.