Google Ads

Proudly Hosted on

About Me

Hi, I 'm Aditya, the guy behind this website and many other. This site acts as my web playground, where I share all about me, my work and my knowledge.

I have over 10.5 yrs hands on experience in PHP, Mysql, JavaScript, open sources CMS like Joomla, Wordpress etc. During these 10.5 years, I have worked on more than 200 projects and/or websites but could not spare time for my blog. But now I am trying to write something whenever I can.

 

 

Ajax AutoComplete

Autocomplete/ Autosuggest is a feature provided by many web browsers, e-mail programs, search engine interfaces, source code editors, database query tools, word processors, and command line interpreters. Autocomplete involves the program predicting a word or phrase that the user wants to type in without the user actually typing it in completely.

Here i am going to demonstrate a simple example of autosuggest. Thi is based on php and ajax. It will fetch country names based on the keyword entered in textbox from the database. We will create three files for this:-

1. First Step :- Make a HTML file containing the textbox

Keyword: <input type="text" id="keyword" name="keyword" 
		onKeyUp="dowork();">
	<div id="ajax_result" style="display:none; 
		width:200px;"></div>

2. Second step:- Create a js file

function getHttp(){
         var xmlhttp
         try{
		xmlhttp=new XMLHttpRequest();
	}catch(e){
	  try{
	  xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
	  try{
	  xmlhttp=new ActiveXOject("Microsoft.XMLHTTP");
	  }catch(e){
	  alert("Your browser doesnt support Ajax.");
			return false;
			}
		}
		}
	return xmlhttp;
}

//create request
function dowork(){
  var keyword = document.getElementById('keyword').value;
  document.getElementById("ajax_result").style.display="block";
  document.getElementById("ajax_result").innerHTML=
'<img src="images/loading.gif" />'; 
xmlhttp=getHttp(); 
if(xmlhttp){ xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
document.getElementById("ajax_result").innerHTML=xmlhttp.responseText; 
} 
} xmlhttp.open("GET","ajax_server.php?keyword="+keyword, true); 
xmlhttp.send(null); 
} 
}

2. Third step:- Create a php file, which will fetch country name based on keyword from db.

&#39;;
		while($row = mysql_fetch_array($result))
		{
			$str = strtolower($row[&#39;name&#39;]);
			$start = strpos($str,$keyword); 
			$end   = similar_text($str,$keyword); 
			$last = substr($str,$end,strlen($str));
			$first = substr($str,$start,$end);
			
			$final = &#39;<span class="bold">&#39;.$first.&#39;</span>&#39;.$last;
		
			echo &#39;
'.$final.'';
		}
		echo "";
	}
	else
		echo "No Result";
		}
?>	   
	   
Tags: , , ,
Comments are closed.
Home / Ajax AutoComplete