CONTEXT
In order to implement autocomplete (with dropdown suggestions of possible matches) in WordPress I’m using the following code to get back a series of variables from my SQL table:
//DISBLE UPDATE NOTIFICATIONS
add_action('wp_enqueue_scripts', 'se_wp_enqueue_scripts');
function se_wp_enqueue_scripts() {
wp_enqueue_script('suggest');
}
add_action('wp_head', 'se_wp_head');
function se_wp_head() {
?>
<script type="text/javascript">
var se_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery(document).ready(function() {
jQuery('#se_search_element_id').suggest(se_ajax_url + '?action=se_lookup');
});
</script>
<?php
}
add_action('wp_ajax_se_lookup', 'se_lookup');
add_action('wp_ajax_nopriv_se_lookup', 'se_lookup');
function se_lookup() {
global $wpdb;
$search = like_escape($_REQUEST['q']);
$query = 'SELECT DISTINCT meta_value FROM wp_usermeta
WHERE meta_key="company" AND meta_value LIKE '%' . $search . '%'';
foreach ($wpdb->get_results($query) as $row) {
$meta_value = $row->meta_value;
echo $meta_value. "n";
}
die();
}
PROBLEM
Although this returns the correct values (I’m using a Chrome extension to see results of Ajax call in dev tools), nothing is being displayed below the form field. Form field HTML looks like this:
<input type="text" id="se_search_element_id" name="fname">
I’m not sure if the issue is the format that the Ajax call is returning or whether there is something I’m missing that should make the dropdown appear.
The first argument to the suggest function should be an array. You are feeding it a url. So, you don’t need to use ajax. Just do everything in the head: database query (all companies), json_encode results and echo it into the javascript. If you want to do it by ajax take a look at jQuery autocomplete https://www.devbridge.com/sourcery/components/jquery-autocomplete/