i'm trying to create a simple autocomplete textbox that takes the suggestions from an array.the code i'm using(based on this) is :
call.php
<?php
$list = array(
"Autocomplete",
"Metapher",
"Metatag");
for($i=0; $i<count($list); $i++){
if(strpos($list[$i], $_GET['str']) !== FALSE && strlen($_GET['str']) >= 2){
echo str_ireplace($_GET['str'], '<b style="color: red;">'.$_GET['str'].'</b>', $list[$i]) . '<br>';
}
}
?>
index.php
<!DOCTYPE html>
<html>
<head>
<title>AJAX - 03</title>
<script type="text/javascript">
var ajax = new XMLHttpRequest;
function t(){
ajax.open("GET", "call.php?str=" + document.getElementById("test").value, false);
ajax.send();
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
document.getElementById("container").innerHTML = ajax.responseText;
}
}
}
</script>
</head>
<body>
<div id="container" style="border: 3px; border-style: solid; font-size: 42pt; border-radius: 7px;">
Text
</div>
<br><br>
<input id="test" type="text" onkeyup="javascript:t()">
</body>
</html>
but nothing comes up at the suggestion box.I can't find any syntax errors so i suppose there is something wrong with the logic?
UPDATE: after the advice from PLB and FAngel i added the onreadystatechange and the checks.However it still doesn;t work properly.Actually i just found that if you type a compination of letters that are inside one of the 3 words the suggestions come up properly.It just doesnt work if you type the starting letters of a word.For example if i give "com" as input the word Autocomplete comes up.However if i give "Aut" then nothing.So i guess the actual problem is here:
if(**strpos($list[$i], $_GET['str']) !== FALSE** && strlen($_GET['str']) >= 2)
From what i read here http://php.net/manual/en/function.strpos.php the problem could be the use of != but i use !== as i should.Any thoughts?
It totally WORKS!
I tried it.
I had input : Met
and it gave me Metaphor and one more word.
However, for advanced usage. Check this out, you gonna love it.
You are missing that your request is asynchronous. So when you run this line: document.getElementById("container").innerHTML = ajax.responseText;
, request is not done yet. Take a look at this . onreadystatechange
is what you need. Or make that call synchronous
You can also work it like this.
All you need is you just replace the json array with php jsonencoding like this
$list = array(
"Autocomplete",
"Metapher",
"Metatag");
<script>
var availableTags = <?php echo json_encode($list) ?>
</script>
Hope this will help.