I am using the <form>
tag to make a search bar and submit
button. I would like my submit
button to both query database and show a hidden <div>
. The hidden div
contains the database that will show the results.
I've successfully been able to query database, and display 'div
upon submit, but my problem is getting them to work together. Currently, I have to turn one off to make the other work. Together, the submit
button causes page to refresh thus hiding div again. I have been told making an AJAX
call will solve problem but need help in the code. More specifically the proper syntax for the AJAX
call and if I'm missing anything in my views.py
.
index.html:
<form method="GET" action="">
<input type='text' name='q' value='{{ request.GET.q }}'></input>
<input type='submit' onclick='showDiv()'></input>
</form>
(hidden) div:
<div id="hiddenDiv" style="display: none;">
<p>This is hidden search results<p>
</div>
views.py:
def index(request):
var_1 = Products.objects.all()
var_2 = request.GET.get("q")
if var_2:
var_1 = items.filter(
Q(First__icontains=var_2) |
Q(Last__icontains=var_2)
)
context = {'items': items,
}
return render(request, 'app/index.html', context)
broken javascript (not sure how to move querystring along):
$(document).ready(function(){
$("form").submit(function(e){
e.preventDefault(); //stop submit
$.ajax({ //insert AJAX
type: "GET",
url "app/index.html",
data: {
'var_2': 'var_2'.val() //take querystring
},
success:function showDiv(){ //activate javascript
document.getElementById("welcomeDiv").style.display = "block";
}
});
});
});