ajax live search,javascript - AJAX Live Search Not Showing Results - Stack Overflow

钱凌
2023-12-01

Have a live search page as shown in livesearch.php below, when typing entries into the input box am not getting any results show under it. The html code and script in search.php are shown beelow.

search.php

Search Schedules

Enter any information you wish, this will search all schedule fields.

$(document).ready(function() {

$('#keyword').on('input', function() {

var searchKeyword = $(this).val();

if (searchKeyword.length >= 3) {

$.post('livesearch.php', { keywords: searchKeyword }, function(data) {

$('ul#liveSearch').empty()

$.each(data, function() {

$('ul#liveSearch').append('

' + this.title + '');

});

}, "json");

}

});

});

The livesearch.php that is being referenced by the script is shown below

livesearch.php

session_start();

require 'dbconnect.php';

echo "Keyword: ".$_POST['keywords']."
";

$liveSearchArray = array();

if (!empty($_POST['keywords'])) {

$keywords = $connection->real_escape_string($_POST['keywords']);

$sql = "SELECT OWNER_SURNAME,OWNER_FIRSTNAMES,OWNER_TITLE FROM testucm_owners WHERE OWNER_SURNAME LIKE '%".$keywords."%'";

$result = $connection->query($sql);

if ($result->num_rows > 0) {

echo "We Have A Result, There Are ".$result->num_rows." Rows";

while ($obj = $result->fetch_object()) {

$liveSearchArray[] = array('id' => $obj->OWNER_SURNAME, 'title' => $obj->OWNER_TITLE);

}

} else {

echo "No Matches";

}

}

echo json_encode($liveSearchArray);

mysqli_close($connection);

?>

If a manually add a value for keywords into the livesearch.php query I get the correct results, however no resutls display if I enter search terms via search.php. I have partially test this by putting an alert after var searchKeyword = $(this).val();, this shows the correct term as typed in however still no results showing.

I suspect the error may be with this line of code:

$('ul#liveSearch').append('

' + this.title + '');

Either that or for some reason the $liveSearchArray is not being passed back to the script, however I'm unable to determine where the error lies or how to fix it. Any help would be greatly appreciated

 类似资料: