How to: Create an Ajax-based Auto-completing Search Field for your Wordpress Theme
Why not helping your visitors to find what they’re looking for on your blog, by using a cool auto-completion on your search field? To do so, we’ll use Wordpress tagcloud, php and ajax.
Please note that even if this code is fully functional, this is an experimentation, and the SQL query isn’t really optimized.
The idea
We will use tags as a list of keyword to suggest to the readers.
When someone will start to type on the search field, we will use Javascript to send a request to a php page which will do the following SQL request SELECT * FROM matable WHERE ‘name’ LIKE ‘$search%’. Via Ajax, we’ll send back the request results to our page, and display it to the visitor.

First part: PHP
The first thing to do is to create a php page. This page will send a request to our WP database and display the tags as a html unordered list.
<?php
if (isset($_POST['search'])) {
$search = htmlentities($_POST['search']);
} else $search ='';
$db = mysql_connect('localhost','root',''); //Don't forget to change
mysql_select_db('wp', $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();
?>
This code is simple: It receive a POST parameter (The letter(s) typed in the search field by the visitor) and then sends a request to our WP database in order to gets all tags starting with the letter(s) typed in the search box.
Part two: Ajax
Now it’s time to start the client-side programming. We need to code 4 Javascript functions in order to make our auto-completion work:
- Function ajax() will create a XMLHTTPRequest object.
- Function request() will send an Ajax request to our gettags.php file.
- Function return() will return gettags.php contents.
- And the selected() function will update the search field.
Here’s our gettags.js file and the 4 functions needed:
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", "wp-content/themes/openbook-fr/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";
}
Part three: Editing your theme
Now that we have our php and javascript ready, we can edit the searchform.php file from your WP theme:
Your searchform.php file should look like this:
<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
<div>
<input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" />
</div>
</form>
We have to add a div, which will display the received data from the request, as well as a Javascript event on the search form:
<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
<div>
<input type="text" value="<?php the_search_query(); ?>" name="s" id="s" onkeyup="request(this.value);"/>
<input type="submit" id="searchsubmit" value="Search" class="button" />
</div>
<div id="tag_update"></div>
</form>
Final part: CSS
Due to the fact that every theme use different color schemes, this is only an example. Anyways, I thought it could be a good start:
#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: #1B1B1C;
text-align: left;
}
#tag_update a:hover{
color: #fff;
background-color: #373737;
background-image: none;
}
That’s all. You now have a very nice auto-completing search form! If you have any questions, feel free to leave a comment below.
Is Your WordPress Site Hackable?
This guest post was written by Hayes Potter, who is a 13 year old programmer and web developer that gives webmasters tips on protecting their website from common hacking techniques. If you have webmaster or WordPress knowledge and are interested in writing a post for Hack WordPress, please contact us.
Today I want to ask all the web masters out there “Is your site hackable?”. I’m a test hacker, and I’ve seen some very popular sites get hacked in some of the simplest ways. Hacking wordpress is actually quite easy if you know what your doing. Two words my friend, “SQL Injections”, most people bypass this thought when they make a blog. Even know wordpress login forms prevent SQL Injections but what about form making plugins? Always check to see if your site is hackable through SQL Injections, for more information on simple hacking with SQL Injection visit my post about it by clicking here.
Also if you have a “robots.txt” file in your home directory, keep in mind that disallowing search engines doesn’t disallow people! Never leave directories with password’s in them, even if it is encrypted. If you have to password protect the director and/or password file. Also always keep your cgi-bin password protected because a lot of file management systems use it to keep passwords that you use. I know some cPanel file management systems do. So always check your site for rogue password files and SQL Injection prevention.
Editor’s Note: If you aren’t very familiar with some of this terminology, your best bet is to always keep your WordPress blogs upgraded to the latest version of WordPress.
Learning More About Javascript Injections
Ok, for those of you who don’t know what javascript injections are, they are ways to manipulate the page source of any web page. Some very simple javascript injections are to simply display an alert box with any text you want. To execute any form of javascript injection enter “javascript:” in the URL bar in your browser, then after the colon you can enter any javascript code in the same way you would in a normal web page. For example if you type in “javascript:var a = “hello world!”; alert(a)” in the URL bar an alert box would pop-up displaying the value of the variable “a”.
Now that you know the basics to javascript injections lets learn how to hack with them, as you should know javascript can manipulate anything on a web page. Here is a simple way to hack into a username on a website. Although the site you try to hack you have to be logged into that site. Once logged in type in the following javascript injection in the URL bar: “javascript:alert(document.cookie)”. This will display the cookie information that the site has on you, look for something like “user_id=xxx” or “PHPSESSID=xxx”. Typically you want to change this string’s value to 1, because the administrator is usually user_id number 1. To change it type in the following in the URL bar: “javascript:void(document.cookie user_id=1);alert(document.cookie);”. Now the user_id’s value should be 1, so refresh the page and you should be logged in as the administrator.
Please remember that you should never mess around with someones site. Always contact the administrator if you find a security hole in their site. Now remember how I said javascript can manipulate anything on a webpage? Well lets start manipulating stuff, for the basics we can just start with forms. Lets say a web page has a form to buy something using a debit card or something like that. Lets say the price for this item is fifty dollars, now lets manipulate this price. Lets say the submit button is a form itself, and it has no other values. In the URL bar type the following: “javascript:void(document.forms[0] = $1.00)”. Ultimately this will change price to one dollar, yes! The “[0]” represents the form number on the page, for example if there are 3 forms on a page. The first one would be labeled “0″ the second one “1″ and the third one “2″.

















