Akash Desai
Akash Desai

Reputation: 602

Materialize autocomplete using php, mysql and jQuery

I'm using materialize autocomplete to get suggestion list from my database table. I give the source as php file in which I'm echoing the json file. Below is the code. It's not working. why?

index.php

<div class="input-field ">
<input type="text" name="t" id="t" class="autocomplete">
</div>
<script>
$(function () {
$('input.autocomplete').autocomplete({
source: 'suggest.php?key=%QUERY'

});
});    
</script>

suggest.php

<?php
$key=$_GET['key'];
$array = array();
$conn = mysqli_connect('localhost', 'root', '', 'home_services');

$query= "select * from worker where lname LIKE '%{$key}%'"; 
$res = mysqli_query($conn, $query);

if($res->num_rows>0){
while($row=$res->fetch_assoc()){
$lname[]= trim($row["lname"]);

}
}
echo json_encode($lname);
?>

Upvotes: 0

Views: 1019

Answers (1)

VaaChar
VaaChar

Reputation: 688

The Materialize autocomplete doesn't have a source option that automatically loads a provided URL.

When you take a look at the documentation you can see that you have to initialize your autocomplete like this:

$('input.autocomplete').autocomplete({
    data: {
        "Apple": null,
        "Microsoft": null,
        "Google": 'https://placehold.it/250x250'
    },
});

The data option accepts a string name with an optional icon string.

You will need to pull your autocomplete data before initializing your autocomplete and provide the data to it while initializing:

$(document).ready(function(){
    $(document).on('input', 'input.autocomplete', function() {
        let inputText = $(this).val();

        $.get('suggest.php?key=' + inputText)
            .done(function(suggestions) {
                $('input.autocomplete').autocomplete({
                    data: suggestions
                });
            });
    });
});

Also you will need to adapt your suggest.php to generate a JSON in the format required by the data option of the autocomplete. So you need to change your code like this:

while($row = $res->fetch_assoc()){
    $lname[trim($row["lname"])] = null;
}

EDIT: Also you initialize your array with the name $array but add stuff to a non-existing array named $lname. You should change the $array = array(); to $lname = array();

Upvotes: 1

Related Questions