2

So I've put together a search feature which searches as you type and displays the result in the text field but now the catch is that it won't let me delete easily and is 'thinking' too fast. Any ideas on how to slow this down?

<script>
$(document).ready
(function()
{
    $("#tag").keyup
    (function() 
        {
            var tag= $(this).val();
            if(tag!='')
            {
                $.ajax(
                {
                    type: "GET",
                    url: "autocomplete.php",
                    data: "q=" + tag,  
                    cache: false,
                    success: function(result)
                    {
                        $("#tag").val(result);
                    }
                }
                );
            }
            return false; 
        }
    );
}
);
</script>

and then this

<?php
 $q_incoming=$_GET['q'];
 //$my_data=mysql_real_escape_string($q_incoming);
 $mysqli=mysqli_connect('localhost','XXXXXXX','XXXXXXXX','XXXXX') or die("Database Error");
 $sql = "SELECT auto_complete_suggestions FROM auto_complete WHERE auto_complete_suggestions LIKE '$q_incoming%' LIMIT 0,1";

 $result = mysqli_query($mysqli,$sql) or die(mysqli_error());

 if($result)
 {
  while($row=mysqli_fetch_array($result))
  {
   echo $row['auto_complete_suggestions']."\n";
  }
 }
?>

The thing I think is happening is that if I type "he" it prompts "help" but when i delete the "p" it's going to prompt again since it has "hel" to search on. Any ideas on how to allow it to delete as well as slow the querying down so that you can type a letter at a reasonable typing pace? I could fidget with a timing function or maybe tell it to ignore after a delete?

Thanks!

new2programming
  • 257
  • 1
  • 9
  • 1
    This Q&A may help http://stackoverflow.com/q/18965768/ and http://stackoverflow.com/q/4542863/ – Funk Forty Niner Oct 31 '14 at 16:02
  • When using `mysqli` you should be using parameterized queries and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation to accomplish this because you will create severe [SQL injection bugs](http://bobby-tables.com/). – tadman Oct 31 '14 at 16:10
  • JQuery Autocomplete has the **exact** delay option which you are looking for. If you are against using the full JQuery UI library then go through the source code and figure out how they did it. – MonkeyZeus Oct 31 '14 at 16:12

1 Answers1

2

The easiest way is to use this jQuery plugin: http://benalman.com/projects/jquery-throttle-debounce-plugin/

Have a look at the usage example below "Debouncing". That's exactly what you're looking for.

You should use prepared statements or your application is vulnerable for SQL injections!

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
BreyndotEchse
  • 2,192
  • 14
  • 20