Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda