I want the ajax data to be passed to the add_teacher function in views.py when the "Add Teacher" button is clicked. path('student/add_teacher/', views.add_teacher, name='add_teacher'),
If only the code below is executed, the value is output to the console.
$(function () {
$checkbox = $('.Checked');
$checkbox.click(checkArray);
function checkArray(){
var chkArray = [];
chkArray = $.map($checkbox, function(el){
if(el.checked) { return el.id };
});
console.log(chkArray);
}
);
But when I add a button click condition, the function doesn't work.
$(function () {
$('button.addteacher').on('click',function () {
$checkbox = $('.Checked');
$checkbox.click(checkArray);
function checkArray(){
var chkArray = [];
chkArray = $.map($checkbox, function(el){
if(el.checked) { return el.id };
});
console.log(chkArray);
$.ajax({
url: "/student/add_teacher/",
type: "post",
data: {'chkArray' : chkArray},
headers: { "X-CSRFToken": "{{ csrf_token }}" },
});
}
});
});
The html file looks like this:
<table id="student-list" class="maintable">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Sex</th>
<th>Select</th>
</tr>
</thead>
<tbody>
{% for student in students %}
<tr class="student">
<td>{{ student.name }}</td>
<td>{{ student.age }}</td>
<td>{{ student.sex }}</td>
<td><input type="checkbox" class="Checked" id="{{ student.id }}"></td>
</tr>
{% endfor %}
</tbody>
</table>
<button type="button" class="btn btn-secondary addteacher">Add Teacher</button>
This is how you can use AJAX to have some backend result in Django:
$.ajax({
// I recommend you to use django like url (let ajax_url = "{% url_name %} instead of plain text url"
url: '/student/add_teacher/',
data: {
'chkArray' : chkArray,
},
dataType: "json",
type: 'POST',
// If it is a success
success: function (response) {
// Do what you want with the result
console.log(response.message) // Print the server response
},
error: function(response) {
// Do something in case of error
console.log(response.message)
}
});
But you view must also be ready to handle ajax request :
from django.http import JsonResponse
def my_ajax_view(request):
if request.method == 'POST':
# Do something here with received data
if request.POST['chkArray']
response_data = {'message': 'data is posted', 'status': 200}
else:
response_data = {'message': 'invalid data', 'status': 422}
return JsonResponse(response_data)