• I have implemented a great new search box on my blog using AJAX. You can see it at grebowiec.net. In the search sipmly type what you want to search for (say “linux”) and then do nothing. It will get the results for you. Here are the two files you need to implmenet it:

    search.php (the server side part):
    <?php

    mysql_connect(“HOST”,”USER”,”PASSWORD”);
    @mysql_select_db(“TABLE”) or die(“Freaking db seems to have left”);

    //make sure that string isn’t in use
    $search = $_REQUEST[‘val’];
    $sql = “SELECT * FROM wp_posts WHERE post_title LIKE ‘%$search%’ OR post_content LIKE ‘%$search%'”;
    $result = mysql_query($sql);
    $num = mysql_numrows($result);
    mysql_close();

    $i=0;
    while($i<$num) {
    $id = mysql_result($result,$i,”ID”);
    $title = mysql_result($result,$i,”post_title”);
    ?>
    “><? echo $title ?>
    <?
    $i++;
    }
    if($num == 0) {
    ?>
    No Results on ‘<? echo $search ?>’
    <?
    }

    ?>
    END SEARCH.PHP

    Then on the client side, enter this for searchform.php in your Template editor:
    <input type=”text” name=”searchInput” id=”searchInput”> Search
    <div id=”searchresults”></div>

    <script language=”JavaScript”>

    // from js_util.js by scottandrew.com/junkyard/js/
    function addEvent(elm, evType, fn, useCapture)

    {
    if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
    } else if (elm.attachEvent){
    var r = elm.attachEvent(“on”+evType, fn);
    return r;
    } else {
    alert(“Handler could not be removed”);
    }
    }
    // end from scottandrew.com/junkyard/js/

    var valBox = document.getElementById(“searchInput”);
    var displayBox = document.getElementById(“searchresults”);
    addEvent(valBox, ‘keyup’, doTest, false);
    var keyPressDelay = ”;

    var xmlhttp=false;
    try {
    xmlhttp = new ActiveXObject(“Msxml2.XMLHTTP”);
    } catch (e) {
    try {
    xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”);
    } catch (E) {
    xmlhttp = false;
    }
    }

    if (!xmlhttp && typeof XMLHttpRequest!=’undefined’) {
    xmlhttp = new XMLHttpRequest();
    }

    function doTest() {
    if (keyPressDelay) {
    window.clearTimeout(keyPressDelay);
    }

    if(valBox.value != ”) {
    keyPressDelay = window.setTimeout(‘doSearch()’,800);
    }
    }

    function doSearch() {
    displayBox.innerHTML = “Searching …”;
    xmlhttp.open(“GET”,”search.php?val=”+valBox.value,true);
    xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4) {
    displayBox.innerHTML = xmlhttp.responseText;
    }
    }
    xmlhttp.send(null);
    }
    </script>
    END SEARCHFORM.PHP

    Let me know what you guys think. I think this is a great addition.

Viewing 15 replies - 1 through 15 (of 15 total)
  • Looks good, hopefully it’ll be easier than LiveSearch to install. Would be even better if you could make it into a plugin though!

    I dig how this works on your blog, very nice.

    however, i suspect i may be missing something.

    i replaced my searchform.php and search.php with the conents from your post (above, here) and while it sort of funtions, what happens is this:

    1.) only get search results for ” ” (meaning nothing… and it reports back everything)
    2.) for some reason these’s a header and main index styling on the resulting div and that’s really not pretty…

    can you explain further exactly what you did to get your example working, it’s very simple and looks a lot more promising for widespread use than LiveSearch (which i’ve spent way too much time on and still can’t get working in FireFox.)

    F.

    I think the code is missing a few things. I for one can get it to work on my blog and it only displays the post titles, however they are not linked to their respective posts. The code in the first part for SEARCH.PHP is a little garbled, there is an extra “> and I’m guessing that’s the part that’s missing. It might not have been rendered correctly by bbpress.

    Thread Starter gweedo767

    (@gweedo767)

    Wierd, that posting of search.php is wrong πŸ™‚ Here is a correct version of it:

    <?php

    mysql_connect(“DBHOST”,”DBUSER,”DBPASS”);
    @mysql_select_db(“DATABASE”) or die(“Freaking db seems to have left”);

    //make sure that string isn’t in use
    $search = $_REQUEST[‘val’];
    $sql = “SELECT * FROM wp_posts WHERE post_title LIKE ‘%$search%’ OR post_content LIKE ‘%$search%'”;
    $result = mysql_query($sql);
    $num = mysql_numrows($result);
    mysql_close();

    $i=0;
    while($i<$num) {
    $id = mysql_result($result,$i,”ID”);
    $title = mysql_result($result,$i,”post_title”);
    ?>
    “><? echo $title ?>
    <?
    $i++;
    }
    if($num == 0) {
    ?>
    No Results on ‘<? echo $search ?>’
    <?
    }

    ?>

    END OF PHP

    Of course, be sure to replace things like HOST and DBUSER and what not with their correct values for you.

    That still didn’t render correctly – maybe you could post the code in a text file on your site?

    If you’re posting code in these forums, you need to surround it with backticks. They’re the little left-single-quote dealie which is the unshifted tilde on my US keyboard (to the left of the 1 and below the ESC).

    Thread Starter gweedo767

    (@gweedo767)

    Okay, I updated this post to have a text file with the needed code. You can get the code directly here.

    Enjoy!

    Let me know if you implement it. I am curious to see what people do with it.

    Also…I hope to compe up with some more AJAX based updates for WordPress soon.

    your post #77 produces:

    “Sorry, no posts matched your criteria.”

    but i do have a couple questions from the text file:

    mysql_connect("HOST","USER","PASSWORD");
    @mysql_select_db("TABLE") or die("Freaking db seems to have left");

    How secure is it to include your mysql user and password in the search.php?

    which table would we insert here? the table containing the posts (i assume, but asking to be sure.)

    thnx

    I believe its perfectly safe.
    PHP is a server-side scripting language, meaning that everything that has the <?php ?> tag is converted by the server into (X)HTML before it can be sent out.

    Thread Starter gweedo767

    (@gweedo767)

    It should be safe, but you could optionally just have the script load the wp-config.php file like this:
    require( dirname(__FILE__) . ‘/wp-config.php’ );
    Then just use the variables it sets for your MySQL connection.

    I implemented the code from the text file you posted GweeDo767, but when I do a search the results appear twice. Say I searched for hello, this is what I would get:

    “>Hello world! Hello world!

    The second Hello world! is the link…but the first one is just there.

    Here’s a screenshot:
    http://jpgodlew.com/wpsearch.gif

    How would I go about fixing this? Thanks for the help!

    Forget my last post…made a stupid mistake πŸ˜‰

    Works great for me, but I’m having troubles adding styling to the div “searchresults” – when I add declarations to my stylesheet nothing happens. I deally, I’d like to add a semi-transparent background which overlays whatever is underneath (ie. absolute position with z-index)

    Also, I wanted to add the variable $excerpt to the title of each link, but I can’t get that to work either. Any help would be much appreciated. Thanks!

    Hello,

    Using the last code this works really great, simple and efficient.

    Just one thing : the links provided doesn’t work with pages (at list when using premalinks) so to limit the search to classic posts the sql must be modified like this :

    $sql = "SELECT * FROM cv_posts WHERE post_title LIKE '%$search%' OR post_content LIKE '%$search%' AND post_status NOT LIKE 'static'";

    Congratulations and warm thanks !!

    Hello,

    After working a little bit on it, a much more elegant and efficient solution for the php file :

    <?php
    // source : http://grebowiec.net/wp-content/searchboxcode.txt
    // http://wordpress.org/support/topic/35120?replies=14
    require( dirname(__FILE__) . '/wp-config.php' );
    global $wpdb;
    $before ='';
    $after='';
    $search = $_REQUEST['val'];
    $sql = "SELECT * FROM $wpdb->posts WHERE post_title LIKE '%$search%' OR post_content LIKE '%$search%'";
    $posts = $wpdb->get_results($sql);
    $output = '';
    if ($posts) {
    foreach ($posts as $post) {
    $post_title = stripslashes($post->post_title);
    $id = $post->ID;
    $permalink = get_permalink($post->ID);
    $output .= $before . '<a href="' . $permalink . '" title="' . $post_title.'">' . $post_title . '</a>' . $after;
    }
    } else {
    $output .= "Je n'ai rien trouvΓ© pour ". $search ;
    }
    echo $output;
    ?>

    Main bonuses :
    – use WP BD management : no need to enter DB data
    – use the permalink structure so work much better when permalinks are used (I didn’t test it without permalinks) and work with pages…

    Hope this helps

    Luc

Viewing 15 replies - 1 through 15 (of 15 total)
  • The topic ‘New AJAX based search box’ is closed to new replies.