0

I am using Django+JQuery to implement a "like" function. It is just like a Facebook thumb-up icon: you click it, the number in the label next to the icon will be increased by one, without refreshing the page.

I used $ajax to post data to the views.py in Django. It works fine in the sense that when clicking the icon( type), the data is sent to the server side and update the database. Then I use json.dumps() to update the label. Here is the issue, the FireFox debugger always shows :

"The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature."

And the browser jumps to a page showing only the dict, like {'label_value','5'}, but not ADDING this to the existing HTML.

My views.py code is something like:

if request.method == 'POST':
    response_data = {}
    response_data['label_thumb_up_1'] = c.num_of_liked
    return HttpResponse(json.dumps(response_data, content_type='application/json'))
else:
    return render('some.html')

My javascript code is like:

$('#cform').on('submit',function(event){
        console.log('Form submitted!');
        event.preventDefault();
        create_post();
    });

function create_post(){
    console.log('Create post is working!');
    $.ajax({
        type:'POST',
        url:window.location.href,
        data: $('#combined').serialize(),

        success:function(json){
            alert(json.label_down_3)
            $('#label_down_3').text(json.label_down_3)
            console.log('success')
        },

        error: function(xhr, errmsg, err){
            console.log('error')
            console.log(err)
        }
    });
}

I have referred to this post and tried the solution: The character encoding of the HTML document was not declared. But not working.

Could anyone please point out where the problem might be? Thank you in advance!

Community
  • 1
  • 1
Steven Xie
  • 97
  • 2
  • 9

1 Answers1

0

The problem is in your views. You are not converting the response_data to json properly. Here's what you can do:

views.py

if request.method == 'POST':
    response_data = {}
    response_data['label_thumb_up_1'] = c.num_of_liked
    data = json.dumps(response_data)
    return HttpResponse(data, content_type='application/json')

JS/jQuery

...
success: function(data) {
    alert(data.label_down_3);
    $('#label_down_3').text(data.label_down_3);
    console.log('success');
},
...

To prevent the page from refreshing

Add return false; after the $.ajax function.

$.ajax({
    ...
});
return false;
xyres
  • 20,487
  • 3
  • 56
  • 85