drv
drv

Reputation: 63

passing JSON data to django using AJAX

I am using python3.6 and Django 2.0.3 on Ubuntu 17.10. I'm a bit new to Django and trying to understand it. I have a table with some input fields in the html page where the users will enter data. My AJAX code below gets the data from the table rows and passes it to django view. CSRF is handled as per the django documentation as I have no form in my html.

Here is my AJAX code (using jQuery)

$(document).ready(function() {
    var table = $('#example').DataTable();
    $('button').click( function() {
        var TableData = new Array();
        $('#example tr').each(function(row, tr){
            TableData[row]={
                "id" : $(tr).find('td:eq(0)').text()
                , "student_name" :$(tr).find('td:eq(1)').text()
                , "marks" : $(tr).find('td:eq(2) input', this).val()
                , "is_present" : $(tr).find('td:eq(3) select', this).val()
            }    
        }); 
        TableData.shift();  // first row will be empty - so remove
        TableData = JSON.stringify(TableData);
        alert(TableData);
        $.ajax({
            type: "POST",
            url: "{% url 'result:ajax_update_result' %}",
            dataType: 'json',
            data: TableData,
            success: function(msg){
                alert(msg);
            }
        });
        return false;
    } );
});

Here is the result of the alert call in the above AJAX. The same data is passed to the djago view code which handles this AJAX call.

[{"id":"1","student_name":"Test Student","marks":"0.00","is_present":"1"},{"id":"2","student_name":"Test Student3","marks":"0.00","is_present":"1"}]

Below is my django view for the above AJAX call.

import json
def save_result(request):
    table_data = json.dumps(request.GET.get('TableData'))
    print(table_data)
    return render(request, 'data/dummy.html', {'msg': 'Data Saved.'})

The django console prints null for the above print(table_data) Please note: I used json.loads in the django view code and got a type error.

I am expecting the data from the AJAX call to be passed to the django function and the data printed in console as dictionary.

Upvotes: 1

Views: 4661

Answers (1)

nb1987
nb1987

Reputation: 1410

You should first stringify your JSON data:

$(document).ready(function() {
    var table = $('#example').DataTable();
    $('button').click( function() {
        var TableData = new Array();
        $('#example tr').each(function(row, tr){
            TableData[row]={
                "id" : $(tr).find('td:eq(0)').text()
                , "student_name" :$(tr).find('td:eq(1)').text()
                , "marks" : $(tr).find('td:eq(2) input', this).val()
                , "is_present" : $(tr).find('td:eq(3) select', this).val()
            }    
        }); 
        TableData.shift();  // first row will be empty - so remove
        alert(TableData);
        $.ajax({
            type: "POST",
            url: "{% url 'result:ajax_update_result' %}",
            dataType: 'json',
            data: JSON.stringify({'TableData': TableData}),
            success: function(msg){
                alert(msg);
            }
        });
        return false;
    } );
});

And retrieve it from request.POST:

import json
def save_result(request):
    table_data = json.loads(request.POST.get('TableData'))
    print(table_data)
    return render(request, 'data/dummy.html', {'msg': 'Data Saved.'})

Note I'm using json.loads since your data is now stringified.

EDIT: I just realized you were actually stringifying your TableData...however, you were trying to pull from a non-existent key TableData from request.GET. I believe my updated answer should work for you.

Upvotes: 5

Related Questions