3

I have a searchfield which allows a member to enter a portion of a customer name and have results returned in the same manner as a facebook drop down search would do. I am running into a few roadblocks though:

  1. When the textbox is cleared OR the member clicks anywhere else on the screen, the results being returned are not also cleared and sit on the page until a refresh or page exit. It is really quite annoying.

JS code:

<script type="text/javascript">
$(document).ready(function() {

    $("#searchbox").keyup(function() {
        var searchbox = $(this).val();
        var dataString = 'searchword=' + searchbox;

        if (searchbox.length < 3 ) {} else {
            $.ajax({
                type: "POST",
                url: "contact_search/search.php",
                data: dataString,
                cache: false,
                success: function(html) {

                    $("#display").html(html).show();
                }
            });
        }
        return false;
    });
});
</script>

HTML

<input type="text" id="searchbox" maxlength="20" />
<div id="display"></div>

Search.PHP script

<?php
    if($_POST)
    {
        $q=$_POST['searchword'];

            try {
                $db = new PDO('mysql:host=localhost;dbname=DB', 'USER', 'PW');
                $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $db->beginTransaction();

                $stmt = $db->prepare("SELECT FNAME, LNAME FROM table WHERE FNAME LIKE ? or LNAME LIKE ? ORDER BY ID LIMIT 5");


                $stmt->execute(array('%'.$q.'%', '%'.$q.'%'));

                $foundrows = $db->query("SELECT FOUND_ROWS()")->fetchColumn();

                $db->commit();
            }

            catch (PDOException $e)
            {
                echo "There was a system DB error. <br>".$e->getMessage();          
            }               

        if(isset($foundrows) && $foundrows == 0) {
            echo "<div class='display_box' align='left'>
                No matching results found</div>";
        } else {        

                while($row = $stmt->fetch()) {
                    $fname = $row['FNAME'];
                    $lname = $row['LNAME'];

                    $re_fname='<b>'.$q.'</b>';
                    $re_lname='<b>'.$q.'</b>';

                    $final_fname = str_ireplace($q, $re_fname, $fname);
                    $final_lname = str_ireplace($q, $re_lname, $lname);
    ?>
        <a href="123.php" target="mainFrame" style="text-decoration:none; color:#000;">
        <div class="display_box" align="left">

        <?php echo $final_fname; ?>&nbsp;<?php echo $final_lname; ?><br/>
        </div></a>

    <?php     
                }
        }
    }   
?>

anybody had this issue before? How would I clear the results from my php script if the field was empty or if a click occured on ANY other area of the screen (besides the results returned)?

NOTE:

My page is built with a 4 'page' frame set (top, left, center, middle) so this issue is slightly more complicated than a normal one. When I put the fix into my actual source code (which are php pages) I run into several "blocked due to insecure content" errors.

specifically, the header of every one of my php pages has the following code to prevent logins outside of https connections and to allow for sessions:

<?php
session_start();

if( $_SERVER['SERVER_PORT'] == 80) {
    header('Location:https://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]); 
    die();
} 

?>
JM4
  • 6,740
  • 18
  • 77
  • 125
  • `if (searchbox.length < 3 ) {} else {`, why not `if (searchbox.length >= 3) {` – Harmen Nov 03 '10 at 14:57
  • Harmen - yep. realized this one should have been easy. The page click anywhere (while using frames) is the part really stumping me – JM4 Nov 03 '10 at 15:49
  • I think you should mention the fact that the page is built on frames somewhere in the question as that makes the problem a little more complicated. – jondro Nov 04 '10 at 06:45

3 Answers3

1

This should take care of hiding the search results when clicking somewhere else:

$("body").click(function() {
    $("#display").hide();
});

If you have click handlers returning false, they will prevent the event from bubbling up to the body element. If that is not what you want, you can use event.preventDefault() to prevent the default action without stoping the event propagation.

To hide results when the search term is erased, change this line:

   if (searchbox.length < 3 ) {} else {

to:

   if (searchbox.length < 3 ) {
          $("#display").hide();
   } else {
geon
  • 8,128
  • 3
  • 34
  • 41
  • excellent answer; the last part works perfectly (should have thought about that!). the only issue I'm havin with the first part (as I tried your method above before), is that my search results are in one frame while a click can obviously happen in another. Is there any way to tell the JS function a click anywhere in any frame? – JM4 Nov 03 '10 at 15:46
  • @JM4: Frames are generally a bad idea. If there is not a very good reason to keep them, I'd suggest you get rid of them. You can mimic the separate scrolloing areas with a div with overflow:scroll and a fixed height. Otherwise, have a look at this: http://stackoverflow.com/questions/539504/run-jquery-in-the-context-of-another-frame – geon Nov 06 '10 at 14:15
  • Frames have their place however and some cases necessary in several intranet applications which this site is. Thanks for the link though - i'll take a look further – JM4 Nov 08 '10 at 18:55
1

You can attach a click event to the body element of each of the frames and hide the results there. The dom of the frame is available from the window object like:

window.frames['myframe'].document

and if you need to access the window object from a frame use:

window.parent

that way you can access the results from any frame. The only annoying thing is that you need to add the code for hiding the results in all the frames.

Hope that helps.

J.

EDIT:

To clarify. If you want to hide a div in one of the frames you need to have the hiding code in each frame of your page. Let's say your page has two frames: 'mainFrame' and 'searchFrame' where the search results are.

In the 'mainFrame' you'd have code like this:

$(document).click(function() {
    // second parameter sets the context for the selector
    $("#display", window.parent.frames['searchFrame'].document).hide(); 
})

In the 'searchFrame':

$(document).click(function() {
    $("#display").hide(); 
})
jondro
  • 619
  • 3
  • 9
  • I'm a little confused. Based on the top part of geon's answer below can you explain a little more? – JM4 Nov 03 '10 at 19:23
  • @jondo - running into a new issue though after actually setting up into my page if you wouldn't mind taking a look. – JM4 Nov 04 '10 at 15:46
  • @JM4: I have to say I don't know why it's not working. Can you try without https:// and see if that works. – jondro Nov 04 '10 at 20:29
  • it does work without https but i do in fact need my pages secured with https so it is more than a bit strange. throwing that script in all of my pages also nulls out any javascript from working. – JM4 Nov 04 '10 at 23:05
0

Why not do

if(isset($_POST['searchword']) && $_POST['searchword']) 

Then when you don't set the searchword no html will be generated, resulting in a empty result that will replace the html.

RJD22
  • 10,230
  • 3
  • 28
  • 35
  • that does not address my issue. Your answer seems to imply the results just show up on their own. The field is blank until I enter 3 characters then it does a search. the results of that search are returned (as they should) but they do not clear – JM4 Nov 03 '10 at 15:42