Ajax autosuggest autocomplete from database using php

Posted by Unknown On Thursday 3 January 2013 22 comments


     Ajax auto Suggest is our first article on 2013 .in this article we presenting a simple auto suggest input text field. Here using Ajax, PHP, js and jquery. process of this code snippet follows steps given bellow 

                          
  •  Whenever a key press event on a text box occur, a function in JavaScript is called which uses ajax to send the input in the text box to the name_fetch.php  
  • Then name_fetch.php receives a post request and check for any matches in the database.
  • Matched result is sent back to the JavaScript code, Ajax, and display that bellow text box .  

Program look like
  1. Index.html  :-This is the index file  ,which there is input box and the result to be shown as shown in the image above
  2. script.js :-This file holds the ajax code used to send and receive ajax requests to/from the server.
  3. config.php :-this code contain database connection information.
  4. name_fetch.php :-this code fetch name and send to script.




Download

Download full code

name_fetch.php

       <?php
	include("config.php");
	$keyword = $_POST['data'];
	$sql = "select name from ".$db_table." where ".$db_column." like '".$keyw         ord."%' limit 0,20";
	//$sql = "select name from ".$db_table."";
	$result = mysql_query($sql) or die(mysql_error());
	if(mysql_num_rows($result))
	{
		echo '<ul class="list">';
		while($row = mysql_fetch_array($result))
		{
			$str = strtolower($row['name']);
			$start = strpos($str,$keyword); 
			$end   = similar_text($str,$keyword); 
			$last = substr($str,$end,strlen($str));
			$first = substr($str,$start,$end);
			
			$final = '<span class="bold">'.$first.'</span>'.$last;
		
			echo '<li><a href=\'javascript:void(0);\'>'.$final.'</a><                              /li>';
		}
		echo "</ul>";
	   }
	    else
		echo 0;
     ?>

script.js

       /*
 cc:scriptime.blogspot.in
 edited by :scriptime
*/
$(document).ready(function(){
	$(document).click(function(){
		$("#ajax_response").fadeOut('slow');
	});
	$("#keyword").focus();
	var offset = $("#keyword").offset();
	var width = $("#keyword").width()-2;
	$("#ajax_response").css("left",offset.left); 
	$("#ajax_response").css("width",width);
	$("#keyword").keyup(function(event){
		 //alert(event.keyCode);
		 var keyword = $("#keyword").val();
		 if(keyword.length)
		 {
			 if(event.keyCode != 40 && event.keyCode != 38 && event.keyCode != 13)
			 {
				 $("#loading").css("visibility","visible");
				 $.ajax({
				   type: "POST",
				   url: "name_fetch.php",
				   data: "data="+keyword,
				   success: function(msg){	
					if(msg != 0)
					  $("#ajax_response").fadeIn("slow").html(msg);
					else
					{
					  $("#ajax_response").fadeIn("slow");	
					  $("#ajax_response").html('<div style="text-align:left;">No Matches Found</div>');
					}
					$("#loading").css("visibility","hidden");
				   }
				 });
			 }
			 else
			 {
				switch (event.keyCode)
				{
				 case 40:
				 {
					  found = 0;
					  $("li").each(function(){
						 if($(this).attr("class") == "selected")
							found = 1;
					  });
					  if(found == 1)
					  {
						var sel = $("li[class='selected']");
						sel.next().addClass("selected");
						sel.removeClass("selected");
					  }
					  else
						$("li:first").addClass("selected");
					 }
				 break;
				 case 38:
				 {
					  found = 0;
					  $("li").each(function(){
						 if($(this).attr("class") == "selected")
							found = 1;
					  });
					  if(found == 1)
					  {
						var sel = $("li[class='selected']");
						sel.prev().addClass("selected");
						sel.removeClass("selected");
					  }
					  else
						$("li:last").addClass("selected");
				 }
				 break;
				 case 13:
					$("#ajax_response").fadeOut("slow");
					$("#keyword").val($("li[class='selected'] a").text());
				 break;
				}
			 }
		 }
		 else
			$("#ajax_response").fadeOut("slow");
	});
	$("#ajax_response").mouseover(function(){
		$(this).find("li a:first-child").mouseover(function () {
			  $(this).addClass("selected");
		});
		$(this).find("li a:first-child").mouseout(function () {
			  $(this).removeClass("selected");
		});
		$(this).find("li a:first-child").click(function () {
			  $("#keyword").val($(this).text());
			  $("#ajax_response").fadeOut("slow");
		});
	});
});

Output

      

22 comments:

Unknown said...

its simple and useful.......

Unknown said...

thx...we are looking to make our tuts more interactive .... now our new design on progress

Unknown said...

thanks vmuch... its simple

Unknown said...

thnx thnx nd thanx this is awsum thnx for this :)

Anonymous said...

Hi and thanks for this script. It is perfect!
I am trying now to create dynamic input fields with the same autosuggest. Ex. I have autosuggest names and then I need to click on a button to add new autosuggest field, again for names... Can you please help me with that?

Unknown said...

thank u for ur review ...i think u need to create a new input field dynamically and that also call same ajax ... i mean on click button create a action for new input box...

give me your mail id to my personal mail iris009147@gmail.com i will send you a complete code ..

Unknown said...

Firstly Thanks Alottt!! coz,I tried alot searching code for autosearch but succeeded here!!!
And 1 doubt that...
i filled the list of search options in the database starting with capitals..
when i Entered the search options either capslock on or off its showing its options in starting with small letter...
where should i make the changes in the code...?
Thanks Once Again for the Code!

Anonymous said...

admin pagina (cms)

Anonymous said...

This is exactly what I want. but the code doesn't work :(

Anonymous said...

Hi

This is a very useful code. I have implemented this code, and its working fine but the keyboard up down navigation is not working on drop down results.

Please help

Unknown said...

helloo ... i will check and come back

Raju Kumar said...

nice example

Unknown said...

thx u raj

Saurabh Sharma said...
This comment has been removed by the author.
Saurabh Sharma said...

code is working but please can you tell me when i clear cookies of my browser it's not work well any reason??

manish said...

php code photo tagging


http://www.lessonwithdemo.com/205/ajax/photo-tagging-like-facebook-without-page-refresh-with-ajax-without-jquery.php/

Prof. Dr. T. Ashok Kumar said...

Superb...

Anonymous said...

thanks i really need this

Admin said...

Hi could you tell me if the search functionality is the same as the http://www.geopostcodes.com/ ...this is the most brilliant piece of search box with auto suggest functionality and the keywords coming right from the database and not an imaginary keywords. If this is the not same as the code in this blog how do get a code as in geopostcode website

Admin said...

Hi could you tell me if the search functionality is the same as the http://www.geopostcodes.com/ ...this is the most brilliant piece of search box with auto suggest functionality and the keywords coming right from the database and not an imaginary keywords. If this is the not same as the code in this blog how do get a code as in geopostcode website

Unknown said...

Thank you very much!

Samuel said...

Thanks a lot. Am really blessed with this.

Post a Comment

Fashion