Bocko
Bocko

Reputation: 33

Simple Ajax Autocomplete example, can't get to work with PHP

I saw a video on youtube that did exactly what I try here. I cannot get it to work. This is what I am using: https://www.devbridge.com/sourcery/components/jquery-autocomplete/

I have put all the files under the project folders directly and tried this:

<html>
<head>
<script src="jquery-3.2.1.js"></script>
<script src="jquery.autocomplete.min.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Autocomplete Input</h1>
<input type="text" id="autocomplete"/>

<script>
$('#autocomplete').autocomplete({
    serviceUrl: '/search.php'
});
</script>
</body>
</html>

and search.php is

<?php
echo json_encode(
    array(
        'suggestions' => array(
            'United Arab Emirates',
            'United Kingdom',
            'United States'
        )
    )
);
?>

Simple as it gets, but can't seem to work. I really tried to make this work, if someone could take a look. The styling is correct, the functionality isn't where. Im typing in words starting whit "Un.." and nothing happens.

Upvotes: 0

Views: 426

Answers (1)

rickdenhaan
rickdenhaan

Reputation: 11328

From the webpage you linked: https://www.devbridge.com/sourcery/components/jquery-autocomplete/#jquery-autocomplete-response-format

The response needs to be JSON. If you're echo'ing it yourself, you need to write it as a valid object (note the { and }):

echo '{ "suggestions": ["United Arab Emirates", "United Kingdom", "United States"] }';

Better would be to let PHP handle the JSON formatting:

echo json_encode(
    array(
        'suggestions' => array(
            'United Arab Emirates',
            'United Kingdom',
            'United States'
        )
    )
);

Upvotes: 1

Related Questions