Good evening Coders.
Hi,so i am only getting one results back, for example i have two titles named renew and renew-2 but only get back renew-2 in the results bar. Please see my code for further investigation. What could i be doing wrong
My views.py File:
def Data(request):
items = Post.objects.all()
data = []
for qs in items:
I = {"title":qs.title,
"content": qs.content,
"image": qs.image.url,
}
data.append(I)
return JsonResponse({"data":data})
My HTML File:
{% extends 'blog/base.html' %}
{% load static %}
{% block content %}
<div class = 'w-100 text-center'>
<h1>Search Results</h1>
<form id = "search-form" autocomplete="off">
{% csrf_token %}
<input name = 'game' type="text" id = "search-input" placeholder= "Post Search..">
</form>
<div id = "results-box" class = "results-card not-visible">
</div>
</div>
{% endblock content %}
{% block js %}
<script defer src="{% static 'blog/S1.js' %}"> </script>
{% endblock js %}
My Javascript File:
console.log('Heelowwww')
const url = window.location.href
const searchForm = document.getElementById("search-form")
const searchInput = document.getElementById("search-input")
const resultsBox = document.getElementById("results-box")
const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value
options = {method: "GET",
headers: {
Accept: "application/json"
},
data:{
'csrfmiddlewaretoken': csrf,
}
}
const SearchPosts = async SearchIt => {
const res = await fetch("http://localhost:8000/data/",options)
const Posts = await res.json()
const regex = new RegExp(`^${SearchIt}`, 'gi')
for (var i = 0; i < Posts.data.length; ++i) {
if (Posts.data[i].title.match(regex)){
resultsBox.innerHTML = `<b>${Posts.data[i].title}</b>
<img class="rounded-circle account-img"src = "${Posts.data[i].image}">`
console.log(Posts.data[i].title)
}
}
}
searchInput.addEventListener('input', () => {
SearchPosts(searchInput.value)
if (resultsBox.classList.contains("not-visible")) {
resultsBox.classList.remove("not-visible")
}
})
And should i do the search in the backend? will it improve performance ?