Tales Pádua Tales Pádua - 1 year ago 60
Ajax Question

Can't get AJAX POST working in Django

I can't do a POST ajax request in Django. If I do a GET request, it works fine. I think it may be a csrf token problem, but I can get it to work

My view:

def add_share_points(request):
user = request.user
profile = request.user.profile

if request.method == 'POST':
value = 5.0

# Premia o usuário ao compartilhar conteúdo
description='Você completou seu perfil',

return "ok"

My AJAX request:

$('.my-button').on('click', function(e) {
var pointsCount = $(this).hasClass('homepage-facebook-share') ? 3 : 2;
url: "/add_share_points",
data: {
points: pointsCount,
}).done(function() {
alert('Posting completed.');
alert('Error while posting.');

In my script, I also have this setting:

function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/).test(method);

crossDomain: false,
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader('X-CSRFToken', CSRF_TOKEN);

What is wrong with my code? It gave my a 500 error code, but no further explanation in the logs.

Answer Source

I will point out several things to correct, some are just ways to do it in a django manner and not problems.

In your view

 return HttpResponse(
            json.dumps({'result': 'ok',}),

In your ajax

url: "/add_share_points",

should be:

url : {% url '<name in url.py>' %},

and you need to add (to the data object):

 csrfmiddlewaretoken: '{{ csrf_token }}'

Inside the ajax request, insert this after data:

// handle a successful response
success : function(json) {
     if (json.result=== 'ok'){
         console.log('It works!');
         console.log('Something wrong with response');
// handle a non-successful response
error : function(xhr,errmsg,err) {

In your script

instead of CSRF_TOKEN use '{{ csrf_token }}'

Please use my suggestions and give me feedback and I will update the answer. The two with csfrtoken are probably the problems your having. If you put Django in Debug mode it will be easyer to find out.

My Suggestion

Create a form with what you need to post to gain some features in the validation process.