Uppdaterad
du bör kontrollera dina data som är giltiga och du har några resultat från din databasfråga eller inte, om det inte finns någon post kan du skriva ut meddelande om ej hittad data. Du bör kontrollera utdata från $ExecQuery
och ställ in if
skick enligt det. låt mig nu din produktion och resultat jag hoppas att detta hjälper dig.
Uppdatera ajax.php Senast uppdaterad avsnitt
echo "<li onclick='fill(`".$Result['Name']."`)'>".$Result['Name']."</li>";
Slutför ajax.php
<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_GET['search'])) {
//Search box value assigning to $Name variable.
$Name = $_GET['search'];
//Search query.
$Query = "SELECT Name FROM search WHERE Name LIKE '$Name%' LIMIT 5";
//Query execution
$ExecQuery = MySQLi_query($con, $Query);
//Creating unordered list to display result.
if ($ExecQuery->num_rows > 0) {
echo "<ul>";
while ($Result = MySQLi_fetch_array($ExecQuery)) {
// use the onclick function that defined in js file. you can use the ` sign in js instead of ' if you needed.
echo "<li onclick='fill(`".$Result['Name']."`)'>".$Result['Name']."</li>";
}
echo "</ul>";
}else{
echo "<ul><li>No Result Found!</li></ul>";
}
}
die();
?>
och din ajax-kod.
function fill(value) {
console.log(value);
$('#search').val(value);
$('#display').hide();
}
$(document).ready(function() {
//On pressing a key on "Search box" in "index.php" file. This function will be called.
$("#search").keyup(function() {
//Assigning search box value to javascript variable named as "name".
$('#display').hide();
$('#no-results').css("display", "none");
var name = $('#search').val();
//Validating, if "name" is empty.
if (name == "") {
//Assigning empty value to "display" div in "index.php" file.
$('#no-results').css("display", "block");
}
//If name is not empty.
else {
//AJAX is called.
$.ajax({
//AJAX type is "Post".
type: "GET",
//Data will be sent to "ajax.php".
url: "ajax.php",
//Data, that will be sent to "ajax.php".
data: {
//Assigning value of "name" into "search" variable.
search: name
},
//If result found, this funtion will be called.
success: function(html) {
if (html == '<ul><li>No Result Found!</li></ul>') {
$('#no-results').css("display", "block");
}else{
//Assigning result to "display" div in "index.php" file.
$("#display").html(html).show();
}
}
});
}
});
});
ändra andra delar efter behov.