Skip to content
Permalink
Browse files

Output a JSON encoded array in functions.php

And then tell Awesomplete to update itself
  • Loading branch information...
davidnash committed Jun 22, 2019
1 parent 0142a80 commit 43bb18372ffba3ad1927ffb649fe2bffa9c178ea
Showing with 21 additions and 17 deletions.
  1. +2 −1 functions.php
  2. +19 −16 js/wp-autocomplete.js
@@ -11,7 +11,8 @@ function add_theme_scripts() {
function get_autocomplete() {
if ( isset($_POST['user_input']) ) {
echo $_POST['user_input'];
$list = array( 'aa first item', 'aa second item', 'aa third item', 'aa fourth item' );
echo json_encode( $list );
}
die(); // Stop WordPress from outputting 0
@@ -1,23 +1,26 @@
document.addEventListener('DOMContentLoaded', function() {
// Make sure we're getting the variable/URL from wp_localize_script in functions.php
console.log( 'ajax_url: ' + wp_autocomplete.ajax_url );

var ajax = new XMLHttpRequest();
const min_letters = 2; // how many letters before we start doing AJAX requests
var autocomplete_field = document.getElementById('autocomplete-field');
var awesomeplete_field = new Awesomplete(autocomplete_field);

// Open our autocomplete URL
ajax.open("POST", wp_autocomplete.ajax_url); // From functions.php and wp_localize_script()

// Tell it what sort of data we're sending
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

// Create some sample "input"
var user_input = encodeURI('this is a test');
// When the user presses and releases a key, get the input value
autocomplete_field.addEventListener('keyup', function() {
var user_input = this.value; // Use another variable for developer clarity

// And send it
ajax.send('action=autocomplete_data&user_input=' + user_input);
// If there's enough letters in the field
if ( user_input.length >= min_letters ) {
// Do the AJAX request
ajax.open("POST", wp_autocomplete.ajax_url);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send('action=autocomplete_data&user_input=' + user_input );
}
});

// Output whatever we get back from the AJAX request
// When we get a response from AJAX
ajax.onload = function() {
console.log(ajax.responseText);
}
var json_list = JSON.parse(ajax.responseText); // Parse the JSON from functions.php
awesomeplete_field.list = json_list; // Update the Awesomplete list
awesomeplete_field.evaluate(); // And tell Awesomplete that we've done so
};
});

0 comments on commit 43bb183

Please sign in to comment.
You can’t perform that action at this time.