Last Good Quote: Son's are the seasoning on our lives. - Someone on Facebook

Thursday, April 3

Autocomplete

I think I already wrote this post, but just in case. Here is how I implimented Autocomplete with jQuery:

You will need jquery, I had a copy in my templates, you can find a copy at jquery.com

You will also need autocomplete.js, which I got from here: https://github.com/devbridge/jQuery-Autocomplete/tree/master/scripts

I put the following with my css (in the head of the document)

.autocomplete-suggestions {
border: 1px solid #333;
font-size: 12px;
font-family: arial;
padding: 3px;
background:rgba(93,167,245,0.2);
}
.autocomplete-suggestion
{
padding:3px;
}

I then put the following where I wanted the text box to appear in the HTML code:

Stock: <input type="text" name="txtSymbol" id="txtSymbol">

I then put the following in my document (toward the bottom)
<script>

$(document).ready(function(){
    var options, a;
jQuery(function(){
//options = { serviceUrl:'qryStocks.php' };
var a = $('#txtSymbol').autocomplete({
serviceUrl:'qryStocks.php',
minChars:2,
maxHeight:400,
width:300,
zIndex: 9999,
deferRequestBy: 250, //miliseconds
noCache: false, //default is false, set to true to disable caching
onSelect: function(value, data){ alert('You selected: ' + value.value + ', ' + value.id); }
});

});

});

</script>

Now we also need a file that will return the list to display in our ajax:

<?php
$time_start = microtime(true); 

$conn=new mysqli("localhost","root","ididgood","stock_tracker");

$searchString = $_GET["query"];

$sql = "select distinct symbol, symbol from stock_history where symbol like '$searchString%' order by symbol limit 10";

$result = $conn->query($sql);

$out = "{\"query\":\"$searchString\",";
$suggestions = "";
$data = "";
$i=0;
while ($row = $result->fetch_object()) 
{
if($i> 0) $suggestions.= ",";
if($i> 0) $data.= ",";
$suggestions.= "\"$row->symbol\"";
$data.= "\"$row->symbol\"";
$i++;
}

$out.="\"suggestions\":[$suggestions],\"data\":[$data]}";

print $out;
?>

That's it.

0 comments:

Post a Comment

Followers