Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
How to create a function to pass ajax data when a button is clicked

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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!