Use PHP + JS to implement automatic search prompts (instances)

Source: Internet
Author: User

I think it is necessary for me to write this tutorial, because most of the applications I have seen about Automatic completion only give you a program source code package and then tell you how to use it, instead of telling you how it works and why it does. Knowing this allows you to further customize the plug-in as needed.

Okay. Let's start now.
JavaScript code:

Copy codeThe Code is as follows: <script src = "jquery-1.2.1.pack.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
Function lookup (inputString ){
If (inputString. length = 0 ){
// Hide the suggestion box.
$ ('# Suggestions'). hide ();
} Else {
$. Post ("rpc. php", {queryString: "" + inputString + ""}, function (data ){
If (data. length> 0 ){
$ ('# Suggestions'). show ();
('{Autosuggestionslist'{.html (data );
}
});
}
} // Lookup
Function fill (thisValue ){
$ ('# InputString'). val (thisValue );
$ ('# Suggestions'). hide ();
}
</Script>

JS explanation:
Well, from the code above, we need to connect to a file called rpc. php, which handles all the operations.
The lookup function uses the word obtained from the text input box and uses the Ajax POST method in jQuery to send it to rpc. php.
If the input character 'inputstring' is '0' (Zero), the suggestion box is hidden, which is also user-friendly, if you do not enter anything in the search box, you do not expect a prompt box.
If there is content in the input box, we get this 'inputstring' and pass it to the rpc. php page. Then jQuery's $. post () function is used, as shown below:
$. Post (url, [data], [callback])
The 'callback' part can be associated with a function. This is interesting. It is executed only when data is loaded successfully: <).
If the returned data is not empty (that is, something needs to be displayed), the Search Prompt box is displayed and the returned data (data) is used to replace the html code.
That's easy!
PHP Background Program (rpc. php ):
As you know, all my php background programs are called rpc. php (RPC refers to remote process calls), but they are not named by the functions actually executed, but they are also good.Copy codeThe Code is as follows: // PHP5 Implementation-uses MySQLi.
$ Db = new mysqli ('localhost', 'root', ", 'autocomplete ');
If (! $ Db ){
// Show error if we cannot connect.
Echo 'error: cocould not connect to the database .';
} Else {
// Is there a posted query string?
If (isset ($ _ POST ['querystring']) {
$ QueryString = $ _ POST ['querystring'];
// Is the string length greater than 0?
If (strlen ($ queryString)> 0 ){
// Run the query: We use LIKE '$ queryString %'
// The percentage sign is a wild-card, in my example of countries it works like this...
// $ QueryString = 'uni ';
// Returned data = 'United States, United Kindom ';
$ Query = $ db-> query ("SELECT value FROM countries WHERE value LIKE '$ queryString %' LIMIT 10 ");
If ($ query ){
// While there are results loop through them-fetching an Object (I like PHP5 btw !).
While ($ result = $ query-> fetch_object ()){
// Format the results, im using <li> for the list, you can change it.
// The onClick function fills the textbox with the result.
Echo '<li onclick = "fill (''. $ result-> value. '');">'. $ result-> value. '</li> ';
}
} Else {
Echo 'error: There was a problem with the query .';
}
} Else {
// Dont do anything.
} // There is a queryString.
} Else {
Echo 'there shoshould be no direct access to this script! ';
}
}
?>

PHP code explanation:
Since I have added a lot of comments in the code, I will not detail them here.
Generally, you need to receive the 'querystring' and then use the wildcard character to generate a query statement.
This means that in this case, a query statement is generated every time you type a character. If you do this all the time, I am afraid MYSQL will not be able to stand it. However, in order to simplify the process as much as possible, this approach should be no problem for a small application.
You need to modify this php code slightly in your system. For example, you need to update '$ query' to your own database, and you need to see where to put the name of your database table.
CSS style:
I am using CSS3. My God, it is really useful, although there are functional limitations on Firefox or Safari.Copy codeThe Code is as follows: <style type = "text/css">
. SuggestionsBox {
Position: relative;
Left: 30px;
Margin: 10px 0px 0px 0px;
Width: 200px;
Background-color: #212427;
-Moz-border-radius: 7px;
-Webkit-border-radius: 7px;
Border: 2px solid #000;
Color: # fff;
}
. SuggestionList {
Margin: 0px;
Padding: 0px;
}
. SuggestionList li {
Margin: 0px 0px 3px 0px;
Padding: 3px;
Cursor: pointer;
}
. SuggestionList li: hover {
Background-color: #659CD8;
}
</Style>

CSS code is very standard and there is nothing to mention.
Main file HTML:
This is part of the html code of the main file. You need to add an input box and set the 'onkeyup' function to lookup (this. value ). In addition, I suggest you do not modify its ID, if you do not want to modify the above Javascript code.
:
I think you should want to see what the final effect looks like, OK.

And,

Finally, there is a useful link. I think you should have waited for a long time.
Source File:Click to download

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.