I'm trying to filter table data and then update the table using ajax. I have:
filter form:
<form id="search" method="POST" action="{% url 'article-filter' %}">
<input type="text" class="form-control" id="tokenfield1" name="txtSearch">
<button type="submit" class="btn btn-default js-filter">Submit</button>
</form>
views.py
def article_filter(request):
data = dict()
if request.method == 'POST':
search = request.POST.get('txtSearch')
articles = Article.objects.filter(title = search)
context = {
'articles': articles
}
data['html_table'] = render_to_string('blog/article_table.html',
context,
request = request
)
return JsonResponse(data)
ajax handler:
<script>
var filter =
function() {
$.ajax({
type: "POST",
url: "blog/article-filter",
dataType: 'json',
success: function(response) {
$('#article-table').html(response.html_table);
}
});
};
$("#search").on("submit", ".js-filter", filter);
</script>
But when I submit the form, it only prints out raw html text (the table), how do I actually replace the table within the page and render it?
So the problem was the ajax didn't even happen. I edited the ajax to form submit and not the submit button:
$("#search").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "blog/article-filter",
dataType: 'json',
}).done(function(data) {
$('#article-table').html(data.html_table);
});
});
And it is working just about fine.