Last updated on January 14th, 2022 at 01:19 pm

WordPress categories Auto complete script using PHP ajax

This is a simple script that will automatically display suggestions near the input box when the user start typing words/letters similar to that inside a database/text file/xml.
Here i am using mysql as my back end data provider.
For this i am also getting some data from wordpress. I am displaying the wordpress tags as output in the suggestion area. PHP ajax and some CSS will make the script look elegant.
Here instead of wordpress tags you are very much free to use any back end data for example from a text file, or xml or even some other mysql table, according to your flexibility.

The major one is the php script. This is how it looks for PHP version 5 and Lower

if (isset($_POST['search'])) {
        $search = htmlentities($_POST['search']);
 
$db = mysql_connect('HOSTNAME','USERNAME','PWD'); //Don't forget to change
mysql_select_db('WP+DATABASE', $db);             //theses parameters
$sql = "SELECT name from wp_terms WHERE name LIKE '$search%'";
$req = mysql_query($sql) or die();
echo '<ul>';
while ($data = mysql_fetch_array($req))
{
      echo '<li><a href="#" onclick="selected(this.innerHTML);">'.htmlentities($data['name']).'</a></li>';
}
echo '</ul>';
mysql_close();
exit;
}

For PHP version 5 and above using the MySQLi function

if (isset($_POST['search'])) {
        $search = htmlentities($_POST['search']);

$db = mysqli_connect('localhost','',''); //Don't forget to changes
mysqli_select_db($db,'WP+DATABASE');		     //theses parameters
$sql = "SELECT name from wp_terms WHERE name LIKE '$search%'";
$req = mysqli_query($db,$sql) or die();
echo '<ul>';
while ($data = mysqli_fetch_array($req))
{
      echo '<li><a href="#" onclick="selected(this.innerHTML);">'.htmlentities($data['name']).'</a></li>';
}
echo '</ul>';
mysqli_close($db);
exit();
}


The AJAX / Javascript (no difference since this is client side)

<script data-cfasync="false" type="text/javascript">

var myAjax = ajax();
function ajax() {
        var ajax = null;
        if (window.XMLHttpRequest) {
                try {
                        ajax = new XMLHttpRequest();
                }
                catch(e) {}
        }
        else if (window.ActiveXObject) {
                try {
                        ajax = new ActiveXObject("Msxm12.XMLHTTP");
                }
                catch (e){
                        try{
                                ajax = new ActiveXObject("Microsoft.XMLHTTP");
                        }
                        catch (e) {}
                }
        }
        return ajax;
}
function request(str) {
	//Don't forget to modify the path according to your theme
        myAjax.open("POST", "gettags.php");
        myAjax.onreadystatechange = result;
        myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        myAjax.send("search="+str);
}
function result() {
        if (myAjax.readyState == 4) {
                var liste = myAjax.responseText;
                var cible = document.getElementById('tag_update').innerHTML = liste;
               // document.getElementById('tag_update').style.display = "block";
        }
}
function selected(choice){
        var cible = document.getElementById('s');
        cible.value = choice;
        document.getElementById('tag_update').style.display = "none";
}
</script>

Some style sheet to add color to our result

<STYLE TYPE="text/css">
#tag_update {
        display: block;
        border-left: 1px solid #373737;
        border-right: 1px solid #373737;
        border-bottom: 1px solid #373737;
        position:absolute;
        z-index:1;
}
#tag_update ul {
        margin: 0;
        padding: 0;
        list-style: none;
}
#tag_update li{
        display:block;
        clear:both;
}
#tag_update a {
        width:134px;
        display: block;
        padding: .2em .3em;
        text-decoration: none;
        color: #fff;
        background-color: #2f9737;
        text-align: left;
}
#tag_update a:hover{
        color: #fff;
        background-color: #373737;
        background-image: none;
}
</style>

Last but not the least HTML form to make this magic happen

<form method="get" id="searchform" action="gettags.php">
    <div>
        <input autocomplete="off" type="text" value="" name="s" id="s" onkeyup="request(this.value);"/>
        <input type="submit" id="searchsubmit" value="Search" class="button" />
    </div><div id="tag_update"></div>
</form>


Just put all these scripts on to a file and save it as gettags.php. Thats it 🙂
If you want to disable textbox input history please add this inside the <input > tag of the form.

<input autocomplete="off" type="text" value="" name="s" id="s" onkeyup="request(this.value);"/>


DEMO

5 thoughts on “WordPress categories Auto complete script using PHP ajax”

Leave a Reply

Your email address will not be published. Required fields are marked *