Kode Plus
Kode Plus

Reputation: 706

Fault in Ajax php search

In the following Ajax based search box, if the character is at position 0 then the respective name in the array is not returning but for characters at other positions everything works well. Please fix this...

PHP

$query = $_GET['query'];

$names = array('abc', 'hello', 'cool', 'fun', 'demo', 'test');
foreach($names as $name)
{
$str = strpos($name, $query);

if(!empty($str))
{
    echo "$name ";

}

}

HTML

<form name='myForm'>
Name: <input type='text' onblur="ajaxFunction(this.value);" name='username' /> <br />
Time: <input type='text' disabled="disabled" name='time' />
</form>

AJAX

function ajaxFunction(val) {
var ajaxRequest;

try {
    //Opera, Safari and Firefox xml object
    ajaxRequest = new XMLHttpRequest(); 
} catch(e) {
    try {
        //Internet Explorer xml object
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
        try {
            //Old browser's xml object
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");                   
        } catch(e) {
            return false;
        }
    }

}

ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
        document.myForm.time.value = ajaxRequest.responseText;
    } else {
        //do nothing
    }
}
ajaxRequest.open("GET", "names.php?query="+val, true);
ajaxRequest.send(null); 
}

Upvotes: 0

Views: 88

Answers (2)

skos
skos

Reputation: 4212

You can use the following -

if($str !== FALSE)
{
   echo "$name ";
}

Upvotes: 1

Tony
Tony

Reputation: 3489

That's maybe of the 0 Value returned by strpos (it returns an integer) ... i mean the "if" statement could value it as a false.

Try to compare like

if(strpos($name, $query) === false){ .... do something..... }

Upvotes: 1

Related Questions