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

143
Visualizações
Fetch Data from database and project it on a Datatable using django/ajax

I just recently learned Django/ajax/datatables. I can project my data using a {%for%} loop and im trying to do the same thing with ajax calls.

My view:

def is_ajax(request):
    return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

def getfromServer(request):
    if is_ajax(request=request) and request.method == "GET":
        books= Book.objects.all()
        bookserial = serializers.serialize('json', books)
        return JsonResponse(bookserial, safe=False)
    return JsonResponse({'message':'Wrong validation'})

index.html

<div class="container">
    <table id="books" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Book</th>
                <th>Author</th>
                <th>Genre</th>
                <th>Date Publishedd</th>
                <th>Copies</th>
            </tr>
        </thead>
     </table>
</div>

<script>

        $(document).ready(function() {
            $('#books').DataTable({
                ajax: {
                    type: "GET",
                    datatype : 'json',
                    url: 'views/getfromServer',
                },
                columns: [
            { data: 'name' },
            { data: 'author' },
            { data: 'genre' },
            { data: 'pub_date' },
            { data: 'copies' },
           ]
            });
</script>

Im pretty sure it kinda works this way but i just cant figure it out .

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

jQuery DataTable is a powerful and smart HTML table enhancing plugin provided by jQuery JavaScript library

So it doesn't make sense to put an ajax request inside the .DataTable() method You have to make the ajax request first:

$.ajax({
    type: "GET",
    datatype : 'json',
    url: 'views/getfromServer',
    success: function (result) { // result is the response you get from the server if successful
        // Use the data in result to write the values to your html table respectively here
    }
    error: function (err) {
        // handle error
    }

})

about 4 years ago · Juan Pablo Isaza Relatório

0

thats what I came up with but still doesnt seem to do the trick all i get is an empty table .

 $.ajax({
        type: "GET",
        datatype : 'json',
        url: "views/getfromServer", // "{% url 'index' %}"
        success: function (response) {
            var instant = JSON.parse(response[books]);
            
            for book in books {
                var fields= instant[book]["fields"];
                $("#books tbody").prepend(
                    `<tr>
                        <td>${fields["name"]||""}</td>
                        <td>${fields["author"]||""}</td>
                        <td>${fields["genre"]||""}</td>
                        <td>${fields["pub_date"]||""}</td>
                        <td>${fields["copies"]||""}</td>
                    </tr>`
                )
            }

        },
        error: function (response) {
            alert(response["responseJSON"]["error"]);
        }
    
    })
    $(document).ready(function() {
        $('#books').DataTable();
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