vievs.py
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
def search_result(request):
if is_ajax(request):
res = None
series = request.POST.get('series')
query_se = Games.objects.filter(name__icontains=series)
if len(query_se) > 0 and len(series) > 0:
data = []
for pos in query_se:
item = {
'pk': pos.pk,
'name': pos.name,
'image': pos.image.url,
}
data.append(item)
res = data
else:
res = 'Games not listed'
return JsonResponse({'data': res})
return JsonResponse({})
html
<script>
const sendSearchData = (series) => {
$.ajax({
type: 'POST',
url: '{% url "search" %}',
data: {
'csrfmiddlewaretoken':csrf,
'series':series,
},
success: (res) => {
const data = res.data
if(Array.isArray(data)) {
data.forEach(series => {
result_box.innerHTML += `
<a href="#" class="link">
<div class="row mt-2 mb-2">
<div class="col-2">
<img src="${series.image}" class="game-image" alt="">
</div>
<div class="col-10">
<h5>${series.name}</h5>
</div>
</div>
</a>
`
});
}else{
if(search_input.value.length > 0){
result_box.innerHTML = `<b>${data}</b>`
}else{
result_box.classList.add('not-visible')
}
}
},
error: (err) => {
console.log(err);
}
})
}
const search_form = document.getElementById('search-form')
const search_input = document.getElementById('search-input');
const result_box = document.getElementById('result-box');
const csrf = document.getElementsByName('csrfmiddlewaretoken')[0].value
search_input.addEventListener('keyup', e=>{
if(result_box.classList.contains('not-visible')){
result_box.classList.remove('not-visible')
}
sendSearchData(e.target.value);
});
</script>