Skip to content

Commit

Permalink
Set up basic WordPress AJAX function and test script
Browse files Browse the repository at this point in the history
  • Loading branch information
davidnash committed Mar 20, 2019
1 parent 25fd3f6 commit 0142a80
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
14 changes: 13 additions & 1 deletion functions.php
Expand Up @@ -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');
25 changes: 19 additions & 6 deletions js/wp-autocomplete.js
@@ -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.