Hello everyone,
I begin in everything web related but I have been programming for years. I tried to code something simple : small Mysql DB (works fine) and to begin a search bar to browse data. I adapted a code that I understood provided here : https://www.cloudways.com/blog/live-search-php-mysql-ajax/. Base principle is simple : as you type in your query, it will pass the text to script.js that will forward this request to ajax.php file. In the ajax.php, a javascript function named “fill()” will pass the fetched results. This function will also display the result(s) into “display” div in the “search.php” file.
The problem is that when I type anything it displays, below the search bar, at the moment I type a character:
instead of the actual answer from my database (no error in the browser console).
I tested the SQL query + the user I provide and everything seems fine.
Any clue what could be the root cause ? I strongly suspect a mistake in the code as I already corrected one (script.js instead of scripts.js) but I really cannot figure out where.
Thanks in advance,
problematic code (ajax.php):
<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_POST['search'])) {
//Search box value assigning to $Name variable.
$Name = $_POST['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.
echo '
<ul>
';
//Fetching result from database.
while ($Result = MySQLi_fetch_array($ExecQuery)) {
?>
<!-- Creating unordered list items.
Calling javascript function named as "fill" found in "script.js" file.
By passing fetched result as parameter. -->
<li onclick='fill("<?php echo $Result['Name']; ?>")'>
<a>
<!-- Assigning searched result in "Search box" in "search.php" file. -->
<?php echo $Result['Name']; ?>
</li></a>
<!-- Below php code is just for closing parenthesis. Don't be confused. -->
<?php
}}
?>
</ul>