Using PHP JavaScript to make Ajax search engines

Source: Internet
Author: User
Tags add format functions header php file string variable urlencode
1. Introduction

 A widely used feature in the Web world is search. With the increasing development of Web technology, in order to better meet customer needs, conventional search engines have begun to "open the door" to more unconventional methods. In this regard, Yahoo! is the first to offer its Y! Q service. This new service enables you to search any web page, provided that the author of the page must be included in their web page. It is service technology that enables relevant search results to be presented to readers, thereby showing readers more information without leaving their current page.

HooYahoo! 'S Y! Q service is indeed a great idea, but its appearance has also received some criticism. What is the reason? First, it requires that the client must use Yahoo! 'S JavaScript and you must add a <form /> element in order to satisfy Yahoo!' S search requirements. For many website authors, providing this service requires too much effort. And, after all of these conditions are met, the search results will be presented in Yahoo! style, thus destroying the look and feel of the user's website.

Fortunately, Yahoo! is not the only search engine that provides "Search Results from Your Website" service. MSN Search also provides a similar service, except that it enables web developers to control the look and feel. This capability comes from the RSS version of MSN Search which provides its search results, making it possible to subscribe to a specific search or add the results to your page using Ajax methods.

Although Google has taken the lead in implementing this new "search from your site" technology; at the time of this writing, the Google-related Google BlogSearch Beta was already able to provide the returned results in RSS or Atom format.

2, server-side components

 When performing a search using MSN Search, you will see an orange XML image appear at the bottom of the results page. Clicking on this image will take you to a new page and provide you with the URL to subscribe to the search.

This way, you can write server-side code to retrieve remote feeds. For the search window in this article, you will use PHP to retrieve the search feed. The URL from the server application request information looks like this:

websearch.php? search = [SEARCHTERM]

The query string has only one variable: "search"; therefore, the application should look for this query term. On the server side, you need to create a page to "pull" this data:

<? Php
header ("Content-Type: text / xml");
header ("Cache-Control: no-cache"); if (isset ($ _ GET ["search"]))
Search $ searchTerm = urlencode (stripslashes ($ _ GET ["search"]));
$ Url = "$searchTerm&format=rss";
Xml $ xml = file_get_contents ($ url);
Echo $ xml;
? >

The first two lines set the required headers so that the browser can process the data correctly (in XML format and the results are not buffered). The next line of code uses the isset () function to determine whether the search key exists in the query string.

In order to send a suitable request to a remote host, search terms should be "filtered" through many functions. First, it is passed to the stripslashes () function. If "magic quotes" is enabled in the PHP configuration (supported by default), any quotes that reach the PHP engine are automatically stripped off with a slash (eg, "search query"). The stripslashes () function is responsible for removing these symbols, leaving only "search query". After removing the slash, go to the urlencode () function, which is responsible for encoding characters for use in query strings. Spaces, quotes, "&", etc. are encoded.

NOTE If the search term cannot be "filtered" by these functions, the MSN server will return a code 400- "Bad Request".

When ready to convert search terms, it is included in the URL and stored in the $ url variable. Finally, the file_get_contents () function is responsible for opening the remote file, reading its contents and returning it to the $ xml variable as a string, and then printing it to the page using the echo command.

3, client components

The client code of the search widget in this article is created based on a static object msnWebSearch-it is defined as an object without any attributes (now):

var msnWebSearch = ();

 This object is used to perform a search in the onclick event of an HTMLElement:

< a href = "#"
onclick = ' (event, "Professional Ajax"); return false;' >
Professional Ajax
<// a>

MsThis msnWebSearch object provides several methods for obtaining search results, and is responsible for drawing and placing HTML containing this data. The first method is drawResultBox (), which is responsible for drawing the HTML. The HTML formed by this method looks like this:

<Divclass = "ajaxWebSearchBox">
< div class = "ajaxWebSearchHeading" > MSN Search Results
<a class="ajaxWebSearchCloseLink" href="#"> X </a>
</ Div>
<Div class = "ajaxWebSearchResults">
<a class="ajaxWebSearchLink" target="_new" />
<a class="ajaxWebSearchLink" target="_new" />
</ Div>
</ Div>

The result box is divided into two parts: a header and a result bar (see Figure 1). The header tells the user that this new search window contains results from an MSN search. It also contains an "X" to close the small window. The result bar contains block-style links that will open a new window when clicked.

Making AJAX search engine with PHP JavaScript-ajax search engine
Figure 1. The results box is divided into two parts: a header and a results bar

Fourth, the drawing result user interface

代码 The code to generate this HTML is quite long because the elements in it are all generated using DOM methods. The drawResultBox () method accepts one parameter (an event object):

msnWebSearch.drawResultBox = function (e) {
Var divSearchBox = document.createElement ("div");
Var divHeading = document.createElement ("div");
Var divResultsPane = document.createElement ("div");
Var aCloseLink = document.createElement ("a");

The preceding code creates HTML elements via the createElement () method. After you create these elements, you can start assigning attributes to them. The two elements that complete the termination (closing) above are aCloseLink and divHeading:

aCloseLink.href = "#";
aCloseLink.className = "ajaxWebSearchCloseLink";
aCloseLink.onclick = this.close;
aCloseLink.appendChild (document.createTextNode ("X"));
divHeading.className = "ajaxWebSearchHeading";
divHeading.appendChild (document.createTextNode ("MSN Search Results"));
divHeading.appendChild (aCloseLink);

The first four lines complete the link to close the result box. Among them, the method close () becomes the handler of the onclick event of the link. The next few lines of code are responsible for filling the <div /> in the head with text and closing links.

When this result box is drawn on the page, no response has been received from a server application. In order to show the user what has happened, a message can be shown to the user that the data is loading (which is more friendly) (see Figure 2). To do this, create another element and add it to the divResultsPane element:

var divLoading = document.createElement ("div");
divLoading.appendChild (document.createTextNode ("Loading Search Feed"));

divResultsPane.className = "ajaxWebSearchResults";
divResultsPane.appendChild (divLoading);

This code creates a load message and adds it to the divResultsPane, and also assigns the class name to the divResultsPane.

Making an AJAX search engine with PHP JavaScript
Figure 2. Prompting the user that the data is loading

After completing these elements, all that's left is to add them to the divSearchBox element:

divSearchBox.className = "ajaxWebSearchBox";
divSearchBox.appendChild (divHeading);
divSearchBox.appendChild (divResultsPane);
document.body.appendChild (divSearchBox);

This code is responsible for adding the divHeading and divResultsPane elements to the search window, and adding the search window to the page.

The last step in drawResultBox () is to determine the position of the newly drawn small box and return divSearchBox to its caller:

msnWebSearch.drawResultBox = function (e) {
Var divSearchBox = document.createElement ("div");
Var divHeading = document.createElement ("div");
Var divResultsPane = document.createElement ("div");
Var aCloseLink = document.createElement ("a");
ACloseLink.href = "#";
CloseaCloseLink.className = "ajaxWebSearchCloseLink";
CloseaCloseLink.onclick = this.close;
CloseaCloseLink.appendChild (document.createTextNode ("X"));
DivHeading.className = "ajaxWebSearchHeading";
DivHeading.appendChild (document.createTextNode ("MSN Search Results"));
DivHeading.appendChild (aCloseLink);
Var divLoading = document.createElement ("div");
DivLoading.appendChild (document.createTextNode ("Loading Search Feed"));
DivResultsPane.className = "ajaxWebSearchResults";
DivResultsPane.appendChild (divLoading);
DivSearchBox.className = "ajaxWebSearchBox";
DivSearchBox.appendChild (divHeading);
DivSearchBox.appendChild (divResultsPane);
Document.body.appendChild (divSearchBox);
This.position (e, divSearchBox);
Return divSearchBox;

 After establishing the msnWebSearch object in this way, you must return the divSearchBox to its caller for other operations. As you can guess, the position () method is responsible for placing the search box. It accepts two parameters: the event object passed to drawResultBox () and the divSearchBox element:

msnWebSearch.position = function (e, divSearchBox) {
Var x = e.clientX + document.documentElement.scrollLeft;
Var y = e.clientY + document.documentElement.scrollTop; = x + "px"; = y + "px";

The first two lines of code get the left and top positions for the search results box. Performing this operation requires two types of information. The first is the x and y coordinates of the mouse (this information is stored in the clientX and clientY properties).

However, these coordinates are not enough to correctly position the result box, because the clientX and clientY properties return the mouse position relative to the client area of the browser window, not the actual coordinates in the page. With this in mind, we can use the scrollLeft and scrollTop attributes of the document element. After calculating the final coordinates, you can finally determine the position of the box where the user clicked the mouse.

5 . Show results

The populateResults () method is responsible for populating the results bar with search results. It accepts two parameters: the element containing the result and an XParser object (XParser is a JavaScript-based RSS reader, available for free download from

msnWebSearch.populateResults = function (divResultsPane, oParser) {
Var oFragment = document.createDocumentFragment ();

DivResultsPane.removeChild (divResultsPane.firstChild);

This method generates <a/> elements programmatically and via the DOM method; this way, these elements will be added to a document fragment created on the first line. The next line deletes the loading <div /> element added in drawResultBox ().

The next step is to create this link:

for (var i = 0; i < oParser.items.length; i ++) {
Var oItem = oParser.items [i];

Var aResultLink = document.createElement ("a");
ResultaResultLink.href =;
ResultaResultLink.className = "ajaxWebSearchLink"; = "_new";
ResultaResultLink.appendChild (document.createTextNode (oItem.title.value));

OFragment.appendChild (aResultLink);

This code iterates through the items of the feedback, generates a link from the data, and adds the <a/> element to the end of the document fragment.

When exiting the loop, the document fragment is added to the divResultsPane to display the search results:

divResultsPane.appendChild (oFragment);

6. Close the result box

In order to close the search results box, the msnWebSearch object provides a close () method. The close () method handles the onclick event of the link (closes the small box):

msnWebSearch.close = function () {
Var divSearchBox = this.parentNode.parentNode;
Document.body.removeChild (divSearchBox);

Return false;

The search box isn't actually closed; in fact, it was removed from the document. To do this, you need to retrieve the divSearchBox element. The first line of code does this-by retrieving the parent of the element's parent. Because close () handles the onclick event, this refers to this link. The next line removes the divSearchBox element from the document. The last line returns false, forcing the browser not to follow the default behavior of a link (go to the position marked in the href attribute).

7. Build Search Interface

The last method of the msnWebSearch object is search (), which provides an interface to perform a search. You can call search () with an element's onclick event. It accepts two methods: an event object and search terms: = function (e, sSearchTerm) {
Var divSearchBox = this.drawResultBox (e);
Var url = encodeURI ("websearch.php? Search =" + sSearchTerm);
Var oParser = new XParser (url);
ParoParser.onload = function () {
MsnWebSearch.populateResults (divSearchBox.childNodes [1], oParser);

The first line calls the drawResultBox () method and passes the event e to it. The next line encodes the URL for proper conversion. This URL is passed to the XParser constructor to create a new parser. When the search feedback finishes loading and fills the search box with the results, the onload event handler of the analyzer calls the populateResult () method.
Of course, one reason to build this search box is to make it more suitable for the look of your own site.

8. Custom Web Search Box

With CSS, you can easily customize the search box for your existing site, and make any future redesigns very easy.

The first CSS class to discuss is ajaxWebSearchBox (this class implements the search box). Because the search box determines its position, it must have an absolute position:

Position: absolute;
Background-color: # 0d1e4a;
Width: 500px;
Padding: 1px;

 Absolute position is the only requirement here. All other attributes are optional according to your taste. In this example, the box has a light blue background, a width of 500 pixels, and a padding of 1 pixel on each of the four sides. This padding results in a 1-pixel border around the content of the box.

The next class is ajaxWebSearchHeading, which contains the header text of the box and the close link. To place the close link in the upper right corner, it uses absolute position. For this reason, it requires ajaxWebSearchHeading to use a relative position:

Position: relative;
Background-color: # 1162cc;
Font: bold 14px tahoma;
Height: 21px;
Color: white;
Padding: 3px 0px 0px 2px;

Here, the only required attribute is also the position attribute. Other attributes help give the element a good looking appearance. The background color is light blue, while the text portion is white, 14 pixels tall and in Tahoma font. The element is 21 pixels high and is filled with borders on the top and left.

As mentioned earlier, the location of the closed link is absolute:

Position: absolute;
Right: 5px;
Top: 3px;
Text-decoration: none;
Color: white;
a: hover.ajaxWebSearchCloseLink
Color: red;

The element is placed 5 pixels from the right and 3 pixels from the top (the element is placed in the upper right corner). This link has no text decoration and is white in color. When the user's mouse is over the link, the text color turns red.

Note that no visited or active "fake" classes are used here. This is because the window always ignores the href attribute of this link (it has returned false in its event handler). Therefore, the link is never really active or visited.

Then, the ajaxWebSearchResults class styles the results bar as follows:

Background-color: # d3e5fa;
Padding: 5px;

This element does not require the use of CSS attributes. Existing properties are only used to define the results bar and make it easier to read. The background color is a light blue and has a 5 pixel padding around the edges. Of course, you can customize the style of loading messages:

.ajaxWebSearchResults div
Text-align: center;
Font: bold 14px tahoma;
Color: # 0a246a;

This element does not have a class name, but you can still control its style by using the parent child flag shown in the previous example. This example places the text in the center of the <div /> element and gives it a bold blue font that is 14 pixels tall.

The last element you need to stylize is the result link. These links have a class called ajaxWebSearchLink:

Font: 12px tahoma;
Padding: 2px;
Display: block;
Color: # 0a246a;
a: hover.ajaxWebSearchLink
Color: white;
Background-color: # 316ac5;
a: visited.ajaxWebSearchLink
Color: purple;

The only required property is the display property (set to block). This enables each link to be displayed on its own line. Filling the blanks is about two pixels wide, keeping the links a bit apart, making them easier to read. The font is named Tahoma and is 12 pixels tall. Their color is dark blue, in contrast to the light blue background of ajaxWebSearchResults.

 When the user moves the mouse over these links, the background color is set to blue and the text color is changed to white.

"The" fake "class accessed in the last rule of the previous code is set. This is to give the user a hint of the user interface-they have already been used. By setting the visited "fake" class to show a purple color, users can know that they've already visited that link, saving them time-no longer having to visit a page they might not want to see.

Now let's look at how to implement a search box.

9 Implement Web Search Search Box

Implementing this search box is very simple. First, you must upload the websearch.php file to your web server (of course, PHP must be installed). Then you need an HTML document to reference all the components. The msnWebSearch object depends on the XParser class, which in turn depends on the zXml library (available from You must reference these files:

<! DOCTYPE html PUBLIC "-// W3C // DTD XHTML 1.0 Transitional // EN"
"http: // ">
<Html xml: lang = "en" lang = "en" xmlns = "" >
< meta http-equiv = "Content-Type" content = "text / html; charset = utf-8" / >
<Title> Ajax WebSearch </ title>
< link rel = "stylesheet" type = "text / css" href = "css / websearch.css" / >
<Script type = "text / javascript" src = "js / zxml.js"> // script>
<Script type = "text / javascript" src = "js / xparser.js"> // script>
<Script type = "text / javascript" src = "js / websearch.js"> // script>
</ Head> <body>
</ Body>
</ Html>

In order to perform a search, the () method should be set to the onclick handler of the element:

<! DOCTYPE html PUBLIC "-// W3C // DTD XHTML 1.0 Transitional // EN"
"" >
<Html xml: lang = "en" lang = "en" xmlns = "" >
< meta http-equiv = "Content-Type" content = "text / html; charset = utf-8" / >
<Title> Ajax WebSearch </ title>
< link rel = "stylesheet" type = "text / css" href = "css / websearch.css" / >
<Script type = "text / javascript" src = "js / zxml.js"> // script>
<Script type = "text / javascript" src = "js / xparser.js"> // script>
<Script type = "text / javascript" src = "js / websearch.js"> // script>
</ Head> <body>
< a href = "#" onclick = ' (event, "\" Professional Ajax \ "");
return false; '> Search for "Professional Ajax" </a>
<br /> <br /> <br /> <br />
< a href = "#" onclick = ' (event, "Professional Ajax");
return false; '> Search for Professional Ajax </a>
</ Body>
</ Html>

The first new link performs a search for the exact phrase "Professional Ajax", and the second link searches for each of those words. Also note that false is returned in the onclick event-this forces the browser to ignore the href attribute. Clicking on these links will draw a search box at the cursor position, and your search results will appear here.

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: 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.