PHP and Ajax Live Search

Source: Internet
Author: User
ArticleDirectory
    • Example-HTML form
    • Example:
    • Example:

AJAX can provide users with a more friendly and interactive search experience.

Ajax Live Search

In the following Ajax example, we will demonstrate a real-time search.

Compared with traditional search, real-time search has many advantages:

    • When you type data, the matching result is displayed.
    • Filter the results when you continue typing data.
    • If there are too few results, you can delete characters to get a wider range.
Search the w3school page in the text box below

This example includes four elements:

    • Simple HTML form
    • Javascript
    • PHP page
    • XML document

In this example, the result is searched in an XML document (links. XML. To make this example small and simple, we only provide 8 results.

HTML form

This is an HTML page. It contains a simple HTML form, CSS styles for the form, and links to javascript:

<HTML>  
Example-HTML form

As you can see, the HTML page contains a simple HTML form, in which the text box is named "txt1 ".

The form works like this:

    1. When you press the button in the text box and release the button, an event is triggered.
    2. When an event is triggered, a function named showresult () is executed.
    3. Below the form is the <div> element named "livesearch. It is used as a placeholder for the data returned by showresult ().
Javascript

JavascriptCodeStored in "livesearch. js" connected to HTML documents:

VaR xmlhttpfunction showresult (STR) {If (Str. length = 0) {document. getelementbyid ("livesearch "). innerhtml = ""; document. getelementbyid ("livesearch "). style. border = "0px"; return} XMLHTTP = getxmlhttpobject () if (XMLHTTP = NULL) {alert ("browser does not support HTTP request") return} var url = "livesearch. PHP "url = URL + "? Q = "+ strurl = URL +" & SID = "+ math. random () XMLHTTP. onreadystatechange = statechanged XMLHTTP. open ("get", URL, true) XMLHTTP. send (null)} function statechanged () {If (XMLHTTP. readystate = 4 | XMLHTTP. readystate = "complete") {document. getelementbyid ("livesearch "). innerhtml = XMLHTTP. responsetext; document. getelementbyid ("livesearch "). style. border = "1px solid # a5acb2" ;}} function getxmlhttpobject () {var XMLHTTP = NULL; try {// Firefox, opera 8.0 +, Safari XMLHTTP = new XMLHttpRequest ();} catch (e) {// Internet Explorer try {XMLHTTP = new activexobject ("msxml2.xmlhttp");} catch (e) {XMLHTTP = new activexobject ("Microsoft. XMLHTTP ") ;}} return XMLHTTP ;}
Example:

The example in getxmlhttpobject is the same as that in PHP and Ajax requests.

Showresult () function

This function is executed every time a character is entered in the text box.

If no input is in the text field (Str. Length = 0), this function sets the returned field to null and deletes any surrounding borders.

However, if input exists in the text field, the function is executed:

    1. Define the URL (File Name) sent to the server)
    2. Add the parameter (q) with input box content to the URL
    3. Add a random number to prevent the server from using cached files
    4. Call the getxmlhttpobject function to create an XMLHTTP object and notify this function to execute a function named statechanged when a change is triggered.
    5. Use the given URL to open the XMLHTTP object
    6. Send an HTTP request to the server
Statechanged () function

This function is executed whenever the status of the XMLHTTP object changes.

When the status changes to 4 (or "complete"), the response text is used to fill in the content of the txthint placeholder and set a border around the returned field.

PHP page

The server page called by JavaScript code is a PHP file named "livesearch. php.

The code in "livesearch. php" checks the XML document "links. xml ". The title and URL of some pages on w3school.com.cn.

These codes search for the title of the matching string in the XML file and return the result in HTML:

<? PHP $ xmldoc = new domdocument (); $ xmldoc-> load ("links. XML "); $ x = $ xmldoc-> getelementsbytagname ('link'); // get the Q Parameter from URL $ q =$ _ Get [" Q "]; // lookup all links from the XML file if length of q> 0if (strlen ($ q)> 0) {$ hint = ""; for ($ I = 0; $ I <($ X-> length); $ I ++) {$ Y = $ X-> item ($ I)-> getelementsbytagname ('title '); $ z = $ X-> item ($ I)-> getelementsbytagname ('url'); if ($ Y-> item (0)-> nodetype = 1) {// find a link m Atching the search text if (stristr ($ Y-> item (0)-> childnodes-> item (0)-> nodevalue, $ q )) {if ($ hint = "") {$ hint = "<a href = '". $ Z-> item (0)-> childnodes-> item (0)-> nodevalue. "'target = '_ blank'> ". $ Y-> item (0)-> childnodes-> item (0)-> nodevalue. "</a>";} else {$ hint = $ hint. "<br/> <a href = '". $ Z-> item (0)-> childnodes-> item (0)-> nodevalue. "'target = '_ blank'> ". $ Y-> item (0)-> childnodes-> item (0)-> nodeval UE. "</a> ";}}}}} // set output to "no suggestion" If no hint were found // or to the correct valuesif ($ hint = "") {$ response = "no suggestion ";} else {$ response = $ hint;} // output the responseecho $ response;?>
Example:

If any text (strlen ($ q)> 0) is sent from JavaScript, the following occurs:

    1. PHP creates an xml dom object for the "links. xml" File
    2. Traverse all the "title" elements (nodetypes = 1) to find the name that matches the Javascript data.
    3. Locate the link that contains the correct title and set it to the "$ response" variable. If more than one match is found, all the matches will be added to the variable.
    4. If no match is found, set the $ response variable to "no suggestion"
    5. $ Result is the output sent to the "livesearch" Placeholder

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.