user3163650
user3163650

Reputation: 31

Problem sending information between Django template and views using AJAX call

I used an ajax post request to send some variable from my javascript front end to my python back end. Once it was received by the back end, I want to modify these values and send them back to display on the front end. I need to do this all without refreshing the page.

With my existing code, returning the values to the front end gives me a 'null' or '[object object]' response instead of the actual string/json. I believe the formatting of the variables I'm passing is incorrect, but it's too complicated for me to understand what exactly I'm doing wrong or need to fix.

This is the javascript ajax POST request in my template. I would like the success fuction to display the new data using alert.

var arr = { City: 'Moscow', Age: 25 };

    $.post({
        headers: { "X-CSRFToken": '{{csrf_token}}' },
        url: `http://www.joedelistraty.com/user/applications/1/normalize`,
        data: {arr},
        dataType: "json",
        contentType : "application/json",
        success: function(norm_data) {
            var norm_data = norm_data.toString();
            alert( norm_data );
        }
    });

This is my Django URLs code to receive the request:

path('applications/1/normalize', views.normalize, name="normalize")

This is the python view to retrieve the code and send it back to the javascript file:

from django.http import JsonResponse

def normalize(request,*argv,**kwargs):
    norm_data = request.POST.get(*argv, 'true')
    return JsonResponse(norm_data, safe = False)

Upvotes: 0

Views: 136

Answers (2)

Aditya Pudipeddi
Aditya Pudipeddi

Reputation: 41

I've observed that there's a difference between POST data being sent by a form and POST data being sent by this AJAX request. The data being sent through a form would be form-encoded whereas you are sending raw JSON data. Using request.body would solve the issue

from django.http import JsonResponse

def normalize(request):
    data = request.body.decode('utf-8')
    #data now is a string with all the the JSON data.
    #data is like this now "arr%5BCity%5D=Moscow&arr%5BAge%5D=25"
    data = data.split("&")
    data = {item.split("%5D")[0].split("%5B")[1] : item.split("=")[1] for item in data}
    #data is like this now "{'City': 'Moscow', 'Age': '25'}"

    return JsonResponse(data, safe= False)

Upvotes: 0

Martin Nowosad
Martin Nowosad

Reputation: 826

You need to parse your Object to an actual json string. The .toString() will only print out the implementation of an objects toString() method, which is its string representation. By default an object does not print out its json format by just calling toString(). You might be looking for JSON.stringify(obj)

$.post({
headers: { "X-CSRFToken": '{{csrf_token}}' },
url: `http://www.joedelistraty.com/user/applications/1/normalize`,
data: {arr},
dataType: "json",
contentType : "application/json",
success: function(norm_data) {
    var norm_data = JSON.stringify(norm_data);
    alert( norm_data );
}});

Upvotes: 1

Related Questions