Using jquery+ajax+php to implement search box functionality

Source: Internet
Author: User
Tags dsn browser cache

The first is the client

Create a new input box

< input   type = "text" ID = "keyword" name = "keyword" />  

Create a div below the input box and let him hide it first.

<id= "SearchBox"  display:none"></div>   

Note: The search box positioning can use absolute positioning, under the input box, the search button can be added next to the input box, also use absolute positioning

The next step is to send an AJAX request using JQ (JSON-formatted data is used here)

<Script>$ (document). Ready (function(){          varXHR=NULL; $('input[name= "keyword"]'). KeyUp (function() {                if(XHR) {xhr.abort ();//If there is an AJAX request, discard the request              }              varInputtext=$.trim ( This. Value); if(Inputtext!=""){//detects if the contents of the keyboard input are empty and does not make a requestXHR=$.ajax ({type:'GET', URL:'service/suggestion.php', Cache:false,//do not load request information from the browser cacheData:"keyword=" +Inputtext,//data sent to the server sideDataType:'JSON',//the type of the server return data is JSONSuccess:function(JSON) {if(Json.length!= 0) {//detects whether the returned result is empty                        varlists= "<ul>"; $.each (JSON,function() {lists+= "<li>"+ This. Pd_name+"</li>";//iterate through each of the returned data                        }); Lists+="</ul>"; $("#searchBox"). HTML (lists). Show ();//Show the results of your search                          $("Li"). Click (function(){                              $("#keyword"). Val ($ ( This). text ());//Clicking on an Li will get the current value                            $("#searchBox"). Hide (); })                        } Else {                          $("#searchBox"). Hide ();              }                      }                }); }Else{                  $("#searchBox"). Hide ();//Hide Search box without query results}}). blur (function(){              $("#searchBox"). Hide ();//Hide the search box when the input box loses focus        });  }); </Script>  

The server uses PHP statements to connect to the database and then queries (using the PDO connection method)

<?PHPSession_Start(); functionConnectdb () {//functions to connect to a database$db _server= "localhost"; $db _name= "Test";//name of the database$db _user= "Root";//The user name of the database, different user permissions are different$db _pwd="";//password for the database$dsn= "mysql:host=$db _server;d bname=$db _name; Charset=utf8 ";//connect to the database using the PDO method  Try{  $connect=NewPDO ($dsn,$db _user,$db _pwd,Array(pdo::attr_persistent=>true));//If you need a long database connection, you need to add one last parameter  }  Catch(pdoexception$e){      Exit(' Database connection failed '); }      return $connect; }    functionTest$keyword){//functions to find keywords from the database$db=Connectdb (); $result=$db->prepare ("Select field name from database name where field name like?")); $result->bindparam (1,$keyword);//the value of the first question mark$result=Execute; return $result->fetchall (PDO::FETCH_ASSOC); }    $keyword=$_get[' keyword '];//get the contents of the input box  $suggestion=test ($keyword); EchoJson_encode ($suggestion);//Results of output query (JSON format output)?>

Note: Service-side functions are best written on other pages for easy administration.


In this way, the function of the search box can be implemented. Study notes, for reference only ~ ~

Using jquery+ajax+php to implement search box functionality

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.