PHP jQuery Autocomplete
This script was made for http://www.fotozunic.com/shop , where you can see live example of it.
It uses PHP&MySQL, HTML, and jQuery Javascript.
The code is pretty self explaining, sorry for localized language variables.
Have fun!
If you have any trouble mail me at info@webarto.com
PHP:
/**
* @author webarto.com
* @copyright 2010
*/
include("baza.php"); // Includes connection to database
$q = preg_replace("/[^a-zA-Z0-9]/","",$_GET["q"]); // Search string, with alphanumeric sanitization
$min = 1; // Minimum length of query
$limit = 0; // Set limit of results, define if you have large database eg 30
if($limit > 0){
$query = "SELECT id,brand,naslov FROM artikli WHERE naslov LIKE '%$q%' ORDER BY naslov ASC LIMIT $limit";
}else{
$query = "SELECT id,brand,naslov FROM artikli WHERE naslov LIKE '%$q%' ORDER BY naslov ASC";
}
if(strlen($q)>$min){
$sqlq = mysql_query($query);
while($sql = mysql_fetch_array($sqlq)){
$rezultat = str_replace($q,"<span style=\"color:#ff0000;\">".$q."</span>",strtolower($sql["naslov"])); echo '<li><a href="/'.$sql["id"].'/'.google($sql["brand"]." ".$sql["naslov"]).'">'.ucwords($rezultat).'</a></li>';
}
}
HTML:
<h2>Pretraga</h2>
<input type="text" id="pretraga" name="pretraga" onclick="javascript:$(this).val('');" onkeyup="javascript:pretrazi();" size="35" value="Unesite kriterij"/>
</form>
<img alt="" id="ajax" src="/gfx/ajaxmini.gif" style="display:none;"/>
<ul id="rezultati">
<li></li>
</ul>
JavaScript:
function pretrazi(){
$("#ajax").show(); $("#rezultati").load("/autocompleter.php?q="+$("#pretraga").val()); $("#ajax").hide();
}