Skip to content

Instantly share code, notes, and snippets.

@phillro
Created September 4, 2011 18:10
Show Gist options
  • Save phillro/1193253 to your computer and use it in GitHub Desktop.
Save phillro/1193253 to your computer and use it in GitHub Desktop.
Elasticsearch autocomplete example with cross origin resource sharing and authentication
<html>
<head>
<link rel="stylesheet" href="./stylesheets/ui-lightness/jquery-ui-1.8.16.custom.css" type="css">
<script type="text/javascript" src="/javascripts/jquery.min.js"></script>
<script type="text/javascript" src="/javascripts/jquery.base64.min.js"></script>
<script type="text/javascript" src="/javascripts/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="/javascripts/jquery.tmpl.min.js"></script>
</head>
<body>
<script>
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = $.base64.encode(tok);
return "Basic " + hash;
}
var username="YOUR_USERNAME";
var password="YOUR_PASSWORD"
$(function() {
$("#name").autocomplete({
source: function(request, response) {
var wildcard = { "name": "*" + request.term + "*" };
var postData = {
"query": { "wildcard": wildcard },
"fields": ["name", "_id"]
};
$.ajax({
crossDomain:true,
xhrFields: {
withCredentials: true
},
beforeSend:function(req, settings) {
req.setRequestHeader('Authorization', make_base_auth(username,password));
},
url: "https://esh01.elasticsearchhq.com:9200/skyfetch/location/_search",
type: "POST",
dataType: "JSON",
data: JSON.stringify(postData),
success: function(data) {
response($.map(data.hits.hits, function(item) {
return {
label: item.fields.name,
id: item.fields._id
}
}));
},
error: function(error) {
console.log(error);
}
});
},
minLength: 2
})
});
</script>
<div class="demo">
<div class="ui-widget">
<label for="name">Name: </label>
<input id="name">
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment