Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda