Created
February 22, 2017 19:37
-
-
Save fightbulc/a8ef4729759a3bec3ce1c943808fd576 to your computer and use it in GitHub Desktop.
Semantic UI & Algolia search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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