Trying to create a search form .Currently using ajax autocomplete function for this purpose.
<div class="ui-widget">
<label for="search">Search for friends: </label>
<input id="search">
</div>
$(function() {
$("#search").autocomplete({
source: "/accounts/ajax/search/",
minLength: 2,
select: function( event, ui )
});
});
Below is my view that processes my ajax request.
def get_ajax_search(request):
query = request.GET.get('term', '')
print(query)
if request.is_ajax():
qs1 = BasicUser.objects.filter(Q(first_name__icontains=query))
results = []
for user in qs1:
basic_user_json = {}
basic_user_json['id'] = user.pk
basic_user_json['label'] = user.first_name+" "+ user.last_name
basic_user_json['value'] = user.first_name+" "+ user.last_name
results.append(basic_user_json)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
Appreciate your help with a couple of questions:
- How can I redirect to a different page when selecting results. Try something like below example:
Here is a plunker https://plnkr.co/edit/MieqYB6K7inzPVBiinDZ?p=preview
$("#search").autocomplete({
source: "/accounts/ajax/search/",
minLength: 2,
select: function( event, ui ) {
window.open('http://example.com/'+ui.item.value, '_blank')
}
});
- How can I display a user profile picture next to every search result Most importantly
You can follow
jquery autocomplete display custom result
- is there a better way of retrieving data from the database and sending it to the ajax function, assuming it's going to be a high load website. Any ideas or insights would be appreciated.
This is very subjective. You will have to define "better". I suggest use HTML image sources as per the SO question so that at least retrieving those images is asynchronous otherwise your server call will take long time to retrieve inline image data for each item.