How to do Autocomplete in php?
Can any one tell me with example in ajax with javascript.

Recommended Answers

All 2 Replies

I'll give an example, here I'm creating a text box on a web page, when the user is typing in his name, the code looks up possible entries from a text file:

Text file containing names (name.txt):

Aaron
Anton
Bert
Bertrand
...

First let's start with a simple web page (index.html):

<!DOCTYPE html>
<!--Web page for showing a type-ahead function-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Search names</title>
<script type='text/javascript' src='search.js'> </script>
</head>
<body id="main_body" >
    <div id="form_container">
        <h1><a>Start typing a name</a></h1>
        <form id="form_1" class="form"  method="post" action="index.php">
        <label class="description">Name </label><br/>
        <input id="txtName" name="txtname" class="element text medium" type="text" maxlength="255" value=""/> <br/>
        <textarea rows="10" cols="30" id="txtNameList" name="somename"></textarea>
        </form>  
        <div id="footer">
        </div>
    </div>
    </body>
</html>

Now for the PHP-file name.php:

<?php
//PHP code for the type-ahead function

$filename = 'name.txt';//File name containing names
$input = trim($_POST["value"]);//Remove whitespaces 
$output ="";
$buffer;

if (file_exists($filename))//If name file exists
{
    $handle = fopen($filename, "r");//Open file for reading
    while ( ($buffer = fgets($handle) ) !== false)//While data exists
    {
        if ( mb_strtolower(substr($buffer, 0, strlen($input)), 'UTF-8') == mb_strtolower($input, 'UTF-8') )//Check name list for as many characters as user has provided
        {
            $output = $output.$buffer;//Hit - add name
        }
    }
    fclose($handle);//Close the file
    print "$output";//Output the result
}
else
{
print "No such file...";
}
?>

And now for the AJAX code in the javascript search.js:

//JavaScript code for the type ahead function

function init()//Runs when page has fully loaded, sets eventlisteners
{
    txtSearch = document.getElementById("txtName");//Get a reference to the serach box
    txtSearch.addEventListener("keyup", function(){ search(this.value); }, false);//Create an eventlistener for key up
    txtNameList = document.getElementById("txtNameList");//The text box where suggested names wil appear

}

function search(input)
{
    if (input =="")//Clear if no character has been input
    {
        txtNameList.value = "";
        return;
    }
    try
    {
        asynchRequest = new XMLHttpRequest();//Create an asynchrynous XMLHttpRequest object
        asynchRequest.addEventListener("readystatechange", stateChange, false);//What event to listen for, callback function
        asynchRequest.open("POST", "name.php", true);//Use POST, recipient file name.php
        asynchRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        asynchRequest.send("value=" + input);//Send the contents of the search box
    }
    catch (exception)
    {
        alert(exception);
    }
}

function stateChange()
{
    if (asynchRequest.readyState == 4 && asynchRequest.status == 200)//If transferred and without errors
    {
        txtNameList.value = asynchRequest.responseText;//The responseText-property of the asynchronous object
    }
}

var txtSearch;//Variabel for the serach box
var txtNameList;//Variabel for the text result
var asynchRequest;//Variabel for XMLHttpRequest object

window.addEventListener( "load", init, false );//Create an EventListener page loading complete
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.