Hamed Kamrava
Hamed Kamrava

Reputation: 12847

PHP: Create ajax auto-suggest

I would like to create a very simple ajax auto-suggest which it can retrieve some data from database.

You can see here :

index.php

<html>
<head>
<script type="text/javascript">
function suggest() {
    var txtSearch = document.getElementById('txtSearch').value;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
        }
    }
    var target = 'include.inc.php?txtSearch=' + txtSearch;
    xmlhttp.open('GET', target, true);
    xmlhttp.send();
}
</script>
</head>
<body>
<input type="text" id="txtSearch" onkeyup="suggest();"/>
<div id="myDiv"></div>
</body>
</html>

incldue.inc.php

<?php

require_once 'connect.inc.php';

if (isset($_GET['txtSearch'])) {
    $txtSearch = $_GET['txtSearch'];
    getSuggest($txtSearch);
}

function getSuggest($text) {

    $sqlCommand = "SELECT `SurName` FROM `person` WHERE `SurName` LIKE '%$text%'";

    $query = mysql_query($sqlCommand);

    $result_count = mysql_num_rows($query);

    while ($row = mysql_fetch_assoc($query)) {
        echo $row['SurName'].'<br />';
    }

?>

The problem :

Get following error on line 22, But i have no idea why :

Parse error: syntax error, unexpected end of file in C:\wamp\www\PHP_Ajax_Autosuggest\include.inc.php on line 22

P.S :

And i didn't mentioned connect.inc.php content, because it works fine.

Any help would be great appreciated.

Upvotes: 0

Views: 1634

Answers (4)

Rahul
Rahul

Reputation: 1181

<?php

require_once 'connect.inc.php';

 if (isset($_GET['txtSearch'])) {
$txtSearch = $_GET['txtSearch'];
getSuggest($txtSearch);
}

function getSuggest($text) {

$sqlCommand = "SELECT `SurName` FROM `person` WHERE `SurName` LIKE '%$text%'";

$query = mysql_query($sqlCommand);

$result_count = mysql_num_rows($query);

while ($row = mysql_fetch_assoc($query)) {
    echo $row['SurName'].'<br />';
}
} // You forgot this curly brace

?>

It will work fine now.. :)

Upvotes: 1

pinkal vansia
pinkal vansia

Reputation: 10310

you did not close your getSuggest($text) function properly. Just add } before ?>

Upvotes: 2

p e p
p e p

Reputation: 6674

You are just missing a closing brace to close the function. Add that at the end and you should be good. Last three lines should be:

        }
    }
?>

Upvotes: 1

Katana314
Katana314

Reputation: 8620

jothikannan mentioned the quotation marks issue, which makes sense to me. I think you also forgot to end your getSuggest() function, though. Add a } before the ?> in your file.

Upvotes: 1

Related Questions