0

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);
?>

1 Answer 1

1

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();

3
  • It's not working. I didn't understand the jQuery part. And why is $lname data null? Sorry I'm new at jQuery Commented Oct 2, 2018 at 12:58
  • What exactly are you not understanding on the jQuery side? The $lname data is now filled with the name as the key and a value of null because the JSON format that the autocomplete expects is {'name': 'image', ...} or {'name': null, ...}. So you need an array that has the name as the key and either an image or a null as the value so that json_encode will create the correct JSON format from the array.
    – VaaChar
    Commented Oct 2, 2018 at 13:06
  • .done is not working. console says Cannot read property 'done' of undefined Commented Oct 3, 2018 at 15:26

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.