Skip to content
Permalink
Browse files

Set up basic WordPress AJAX function and test script

  • Loading branch information...
davidnash committed Mar 20, 2019
1 parent 25fd3f6 commit 0142a80e2a955eaf075b292d9beb0d61c03d021a
Showing with 32 additions and 7 deletions.
  1. +13 −1 functions.php
  2. +19 −6 js/wp-autocomplete.js
@@ -3,6 +3,18 @@ function add_theme_scripts() {
wp_enqueue_style('awesomepletecss', get_template_directory_uri() . '/awesomplete/awesomplete.css');
wp_enqueue_script('awesompletejs', get_template_directory_uri() . '/awesomplete/awesomplete.js');
wp_enqueue_script('theme-js', get_template_directory_uri() . '/js/wp-autocomplete.js', ['awesompletejs'] );
}
// Allows us to output the ajax_url path for our script
wp_localize_script('theme-js', 'wp_autocomplete', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');
function get_autocomplete() {
if ( isset($_POST['user_input']) ) {
echo $_POST['user_input'];
}
die(); // Stop WordPress from outputting 0
}
add_action('wp_ajax_autocomplete_data', 'get_autocomplete');
add_action('wp_ajax_nopriv_autocomplete_data', 'get_autocomplete');
@@ -1,10 +1,23 @@
document.addEventListener('DOMContentLoaded', function() {
// Awesomplete AJAX demo from https://leaverou.github.io/awesomplete#ajax-example
// 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();
ajax.open("GET", "https://restcountries.eu/rest/v1/lang/en", true);

// 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');

// And send it
ajax.send('action=autocomplete_data&user_input=' + user_input);

// Output whatever we get back from the AJAX request
ajax.onload = function() {
var list = JSON.parse(ajax.responseText).map(function(i) { return i.name; });
new Awesomplete(document.getElementById("autocomplete-field"),{ list: list });
};
ajax.send();
console.log(ajax.responseText);
}
});

0 comments on commit 0142a80

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