I am trying to display a list of users that get updated using AJAX at the same time a new user is added using admin page .
Django 1.9 , Python 3.5 , I am working wi
Welcome to stackoverflow! If you simply wants to call Ajax using Django then You should try this:
views.py
def index(request):
return render(request, 'index.html', locals())
def ajax_view(request):
result = dict()
data_list = []
result['status'] = "success"
for u in User.objects.all():
list_of_user = {'email': u.email, 'first_name': u.first_name}
data_list.append(list_of_user)
result['data'] = data_list
return HttpResponse(json.dumps(result), content_type='application/x-json')
index.html
<script src="/path/to/js/my_ajax.js"></script>
<table class="myTable">
<thead>
</thead>
<tbody>
</tbody>
</table>
my_ajax.js
$( document ).ready(function() {
$.ajax({
type: 'GET',
url: '/ajax/',
success: function (result) {
if (result.status == "success") {
if (result['data']) {
jQuery.each(result['data'], function (i, val) {
$('.myTable').append(
'<tr><td id="first_name">'+val['first_name']+'</td>' +
'<td id="email">'+val['email']+'</td></tr>');
});
}
}
}
})
});
urls.py
url(r'^ajax/$', ajax_view, name='temp'), # Function calls ajax
url(r'^index/$', index, name='index'), # main function redirect to index.html
This will call your ajax and get User's data.