Last active
December 2, 2024 01:29
-
-
Save remyvhw/ce36f5c9674edb27b62e to your computer and use it in GitHub Desktop.
Semantic UI & Algolia search
This file contains 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