PHP and AJAX Suggest
This suggest is similar to google. google is always ahead of the world's technology. Let's take a look at the example below.
First look at the html file.
<Form> First Name: <input type = "text" id = "txt1" onkeyup = "showHint (this. value)"> </form>
<P> Suggestions: <span id = "txtHint"> </span> </p>
The following uses the ajax file of the js file to process data.
Var xmlHttp; function showHint (str) {if (str. length = 0) {document. getElementById ("txtHint "). innerHTML = ""; return;} xmlHttp = GetXmlHttpObject (); if (xmlHttp = null) {alert ("Browser does not support HTTP Request"); return ;} var url = "gethint. php "; url = url + "? Q = "+ str; url = 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 ("txtHint "). innerHTML = xmlHttp. responseText ;}}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 ;}
This file only returns data processed by php, and our php file is as follows.
<? Php // Fill up array with names $ a [] = "Anna"; $ a [] = "Brittany"; $ a [] = "Cinderella "; $ a [] = "Diana"; $ a [] = "Eva"; $ a [] = "Fiona"; $ a [] = "Gunda "; $ a [] = "Hege"; $ a [] = "Inga"; $ a [] = "Johanna"; $ a [] = "Kitty "; $ a [] = "Linda"; $ a [] = "Nina"; $ a [] = "Ophelia"; $ a [] = "Petunia "; $ a [] = "Amanda"; $ a [] = "Raquel"; $ a [] = "Cindy"; $ a [] = "Doris "; $ a [] = "Eve"; $ a [] = "Evita"; $ a [] = "Sunniva"; $ a [] = "Tove "; $ a [] = "Unni"; $ a [] = "Violet"; $ a [] = "Liza"; $ a [] = "Elizabeth "; $ a [] = "Ellen"; $ a [] = "Wenche"; $ a [] = "Vicky ";
// Get the q parameter from URL $ q =$ _ GET ["q"];
// Lookup all hints from array if length of q> 0if (strlen ($ q)> 0) {$ hint = ""; for ($ I = 0; $ I <count ($ a); $ I ++) {if (strtolower ($ q) = strtolower (substr ($ a [$ I], 0, strlen ($ q) {if ($ hint = "") {$ hint = $ a [$ I];} else {$ hint = $ hint. ",". $ a [$ I] ;}}// Set output to "no suggestion" if no hint were found // or to the correct valuesif ($ hint = "") {$ response = "no suggestion";} else {$ response = $ hint;} // output the r Esponseecho $ response;?>All right, we have done suggest.