I am making custom autocomplete search box. When my customer starts typing the first letter of a product name, I need to show all products which have that letter in their name. Same logic applies as he continues to type the whole product name. ( I hope my goal is clear)
I added the search box in my page like this:
<form class="search">
<input id="products" name="products" type="text" />
</form>
I included scripts in my header.php like this:
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="//netsh.pp.ua/upwork-demo/1/js/typeahead.js"></script>
I added script into my footer.php like this:
<script>
$(document).ready(function() {
$('input.products').typeahead({
name: 'products',
remote: 'products.php?query=%QUERY'
});
})
</script>
I made mysql.php file in which I make connection to my mysql database and select query like this:
<?php
//CREDENTIALS FOR DB
define ('DBSERVER', 'here I put server name');
define ('DBUSER', 'here I put user name');
define ('DBPASS','here I put password');
define ('DBNAME','here I put database name');
//LET'S INITIATE CONNECT TO DB
$connection = mysqli_connect(DBSERVER, DBUSER, DBPASS) or die("Can't connect to server. Please check credentials and try again");
$result = mysqli_select_db(DBNAME) or die("Can't select database. Please check DB name and try again");
//CREATE QUERY TO DB AND PUT RECEIVED DATA INTO ASSOCIATIVE ARRAY
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysqli_query ("SELECT post_title FROM wp_posts WHERE post_title LIKE '%{$query}%' AND post_type LIKE '%{$query}%'");
$array = array();
while ($row = mysqli_fetch_array($sql)) {
$array[] = array (
'label' => $row['post_title'].', '.$row['post_type'],
'value' => $row['post_title'],
);
}
//RETURN JSON ARRAY
echo json_encode ($array);
}
?>
I put mysql.php to root folder. But when I start typing into search box, it doesn't act as autocomplete at all.
mysql.php
in wordpress, this will likely end bad (but probably not the cause for your current problem)\ – Mark Kaplun Sep 14 '16 at 11:39