0

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)

2 Answers 2

1

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 );
}});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for commenting. I still get 'null' as a response when I change this though.
You are probably not returning a valid json object. Looking at your backend code I can see that you are also not getting the json out of your request correctly. The default value you return is also just 'true' and not a valid json scheme
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.