Skip to content

Instantly share code, notes, and snippets.

@remyvhw
Last active June 22, 2018 08:23
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save remyvhw/ce36f5c9674edb27b62e to your computer and use it in GitHub Desktop.
Save remyvhw/ce36f5c9674edb27b62e to your computer and use it in GitHub Desktop.
Semantic UI & Algolia search
/*
Implementing Semantic UI and Algolia search can be a pain in the but if you're not use to deal with Semantic UI API stuff. This feels a little bit hackish but so far it works well enough; bonus for not needing the Algolia javascript client.
*/
var algolia = {
id: "Algolia app ID",
key: "Public key",
index: "Index name"
};
$('.ui.search')
.search({
cache: false,
apiSettings: {
method: 'post',
url: 'https://' + algolia.id + '-dsn.algolia.net/1/indexes/' + algolia.index + '/query',
beforeXHR: function(xhr) {
// adjust XHR with additional headers
xhr.setRequestHeader ('X-Algolia-API-Key', algolia.key);
xhr.setRequestHeader ('X-Algolia-Application-Id', algolia.id);
return xhr;
},
beforeSend: function(settings) {
// Retrieve the actual query and urlencode it. There's definitely a better way to do this...
settings.data = JSON.stringify({ "params" : "query=" + encodeURIComponent(settings.urlData.query) + "&hitsPerPage=5" });
return settings;
},
onResponse: function(algoliaResponse) {
var
response = {
results : []
}
;
// translate Algolia API response to work with search.
$.each(algoliaResponse.hits, function(index, item) {
// Of course you'll have to adapt this to your needs.
response.results.push({
title : item.title,
url : "/myroute/" + item.id
});
});
return response;
},
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment