<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>WordPress Hacks &#187; javascript</title>
	<atom:link href="http://wphacks.com/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://wphacks.com</link>
	<description>WordPress Themes, Plugins, Hacks, Tutorials, and more!</description>
	<lastBuildDate>Thu, 02 Feb 2012 15:20:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>How to: Create an Ajax-based Auto-completing Search Field for your WordPress Theme</title>
		<link>http://wphacks.com/how-to-create-an-ajax-based-autocompleting-search-field-for-your-wordpress-theme/</link>
		<comments>http://wphacks.com/how-to-create-an-ajax-based-autocompleting-search-field-for-your-wordpress-theme/#comments</comments>
		<pubDate>Wed, 10 Sep 2008 08:00:50 +0000</pubDate>
		<dc:creator>Jean-Baptiste Jung</dc:creator>
				<category><![CDATA[How-To]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[WordPress Code]]></category>
		<category><![CDATA[WordPress Hacks]]></category>
		<category><![CDATA[WordPress How-To]]></category>

		<guid isPermaLink="false">http://wphacks.com/?p=1071</guid>
		<description><![CDATA[Why not helping your visitors to find what they're looking for on your blog, by using a cool autocompletion on your search field? To do so, we'll use Wordpress tagcloud, php and ajax.]]></description>
			<content:encoded><![CDATA[<p style="float: right;margin: 4px;"><a href="http://www.inboundwriter.com/wordpress?utm_source=iw-plugin&utm_medium=Banner%2B300x250&utm_content=SEO&utm_campaign=WPHacks" target="_blank"><img border="0" src="http://wphacks.com/wp-content/themes/WPHacks/images/300x250.gif" width="300" height="250"></a></p><p>Why not helping your visitors to find what they&#8217;re looking for on your blog, by using a cool auto-completion on your search field? To do so, we&#8217;ll use WordPress tagcloud, php and ajax.</p>
<p class="attention">Please note that even if this code is fully functional, this is an experimentation, and the SQL query isn&#8217;t really optimized.</p>
<h2>The idea</h2>
<p>We will use tags as a list of keyword to suggest to the readers.</p>
<p>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 <em>SELECT * FROM matable WHERE &#8216;name&#8217; LIKE &#8216;$search%&#8217;</em>. Via Ajax, we&#8217;ll send back the request results to our page, and display it to the visitor.</p>
<p><img src="http://www.lyxia.org/blog/wp-content/uploads/2008/03/automcompletion-wordpress.png" alt="automcompletion-wordpress.png" /></p>
<h2>First part: PHP</h2>
<p>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.</p>
<pre>&lt;?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 '&lt;ul&gt;';
while ($data = mysql_fetch_array($req))
{
        echo '&lt;li&gt;&lt;a href="#" onclick="selected(this.innerHTML);"&gt;'.htmlentities($data['name']).'&lt;/a&gt;&lt;/li&gt;';
}
echo '&lt;/ul&gt;';
mysql_close();
?&gt;</pre>
<p>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.</p>
<h2>Part two: Ajax</h2>
<p>Now it&#8217;s time to start the client-side programming. We need to code 4 Javascript functions in order to make our auto-completion work:</p>
<ul>
<li>Function <em>ajax()</em> will create a XMLHTTPRequest object.</li>
<li>Function <em>request()</em> will send an Ajax request to our <em>gettags.php</em> file.</li>
<li>Function <em>return()</em> will return <em>gettags.php</em> contents.</li>
<li>And the <em>selected()</em> function will update the search field.</li>
</ul>
<p>Here&#8217;s our <em>gettags.js</em> file and the 4 functions needed:</p>
<pre>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";
}</pre>
<h2>Part three: Editing your theme</h2>
<p>Now that we have our php and javascript ready, we can edit the <em>searchform.php</em> file from your WP theme:</p>
<p>Your <em>searchform.php</em> file should look like this:</p>
<pre>&lt;form method="get" id="searchform" action="&lt;?php bloginfo('url'); ?&gt;/"&gt;
        &lt;div&gt;
                &lt;input type="text" value="&lt;?php the_search_query(); ?&gt;" name="s" id="s" /&gt;
                &lt;input type="submit" id="searchsubmit" value="Search" /&gt;
        &lt;/div&gt;
&lt;/form&gt;</pre>
<p>We have to add a <em>div</em>, which will display the received data from the request, as well as a Javascript event on the search form:</p>
<pre>&lt;form method="get" id="searchform" action="&lt;?php bloginfo('url'); ?&gt;/"&gt;
    &lt;div&gt;
        &lt;input type="text" value="&lt;?php the_search_query(); ?&gt;" name="s" id="s" onkeyup="request(this.value);"/&gt;
        &lt;input type="submit" id="searchsubmit" value="Search" class="button" /&gt;
    &lt;/div&gt;
    &lt;div id="tag_update"&gt;&lt;/div&gt;
&lt;/form&gt;</pre>
<h2>Final part: CSS</h2>
<p>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:</p>
<pre>#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;
}</pre>
<p>That&#8217;s all. You now have a very nice auto-completing search form! If you have any questions, feel free to leave a comment below.</p>
<img src="http://wphacks.com/?ak_action=api_record_view&id=672&type=feed" alt="" /><p></p><p>You are reading <a href="http://wphacks.com/how-to-create-an-ajax-based-autocompleting-search-field-for-your-wordpress-theme/">How to: Create an Ajax-based Auto-completing Search Field for your WordPress Theme</a>  © 2008 | <a href="http://wphacks.com">WordPress Hacks</a> | <a href="http://wpnexus.com">WordPress Directory</a> | <a href="http://wpforums.com/">WordPress Forums</a> | <a href="http://wpebook.com/">WordPress eBook</a></p>

<p><small>Enjoy writing about WordPress?  Get your blog more exposure by joining the <a href="http://wphacks.com/write/">WordPress Hacks writing team</a>!</small></p>]]></content:encoded>
			<wfw:commentRss>http://wphacks.com/how-to-create-an-ajax-based-autocompleting-search-field-for-your-wordpress-theme/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
	</channel>
</rss>

