Skip to content

Instantly share code, notes, and snippets.

@simonw
Created April 27, 2018 06:47
Show Gist options
  • Save simonw/8af1edd6c5c408dc33e963c7f30b286d to your computer and use it in GitHub Desktop.
Save simonw/8af1edd6c5c408dc33e963c7f30b286d to your computer and use it in GitHub Desktop.
Awesomplete ajax example.
<link rel="stylesheet" href="http://leaverou.github.io/awesomplete/awesomplete.css">
<script src="http://leaverou.github.io/awesomplete/awesomplete.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
const input = document.querySelector('input.blah');
const awesomplete = new Awesomplete(input);
input.addEventListener("awesomplete-selectcomplete", (ev) => console.log(ev.text));
input.addEventListener('keyup', (e) => {
var code = (e.keyCode || e.which);
if (code === 37 || code === 38 || code === 39 || code === 40 || code === 27 || code === 13) {
return;
} else {
const murl = 'http://127.0.0.1:8044/MetObjects-00f9d76/Artist+Alpha+Sort.jsono?_search='+input.value + '*';
fetch(murl).then(r => r.json()).then(d => {
awesomplete.list = d.rows.map(row => ({value: row.id, label: row.value}));
});
}
});
});
</script>
<input class="blah" style="width: 400px">
@saltcod
Copy link

saltcod commented Mar 29, 2019

import Awesomplete from 'awesomplete';

/**
 * Add autocompletion to the location search input
 */
const init = () => {
	const input = document.querySelector( 'input[name="location"]' );

	if ( !input ) {
		return;
	}

	const awesomplete = new Awesomplete( input, { tabSelect: true, minChars: 3 } );

	/**
	 * Ajax a new request for posts
	 */
	function ajaxResults() {
		const endpointURL = 'http://site.com/endpoint/?s=' + input.value;

		const ajax = new XMLHttpRequest();
		ajax.open( 'GET', endpointURL, true );

		ajax.onload = () => {
			let list = [];
			if ( 200 === ajax.status ) {
				list = JSON.parse( ajax.responseText ).map( item => {
					return item[0];
				} );
				awesomplete.list = list;
			}
		};

		ajax.send();
	}

	input.addEventListener( 'keyup', ajaxResults );
};

init();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment