Reputation: 189
Trying to make a submission with out rendering the page, But it's not working and the page will rendered when clicking the submit button. How can i update the details form the following field?
Template something like this
{% for i in userlist %}
<form method="POST" id="profileUpdate">
{% csrf_token %}
<input class="email" type="email" value="{{i.email}}" id="email">
<input class="dob" id="dob" type="text" value="{{i.date_of_birth}}" >
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
{% endfor %}
Ajax script
<script>
$(document).on('submit', '#profileUpdate', function (e) {
$.ajax({
type: 'POST',
url: '{% url "profileUpdate" %}',
data: {
email: $('#email').val(),
dob: $('#dob').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
alert("Success");
},
});
});
</script>
views.py
def profileUpdate(request):
response_data = {}
if request.get('action') == 'post':
email=request.POST.get('email')
dob=request.POST.get('dob')
response_data['dob'] = dob
ob=Employee.object.get(email=email)
ob.date_of_birth= dob
ob.save()
return HttpResponse('')
urls.py
urlpatterns = [
path('registeredusers', registeredusers.as_view(), name="registeredusers"),
path('profileUpdate', views.profileUpdate, name='profileUpdate'),
]
Upvotes: 0
Views: 64
Reputation: 2292
Use preventDefault()
to prevent page load.
<script>
$(document).on('submit', '#profileUpdate', function (e) {
e.preventDefault(); //====> Add this line.
$.ajax({
type: 'POST',
url: '{% url "profileUpdate" %}',
data: {
email: $('#email').val(),
dob: $('#dob').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
alert("Success");
},
});
});
</script>
Upvotes: 1