Tales Pádua Tales Pádua - 3 months ago 9
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:

@login_required
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
VirtualCurrencyTransaction.objects.create(
user=request.user,
reason=2,
description='Você completou seu perfil',
value=value
)

return "ok"


My AJAX request:

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


In my script, I also have this setting:

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

$.ajaxSetup({
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

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',}),
            content_type="application/json"
        )

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!');
     }else{
         console.log('Something wrong with response');
     }
// handle a non-successful response
error : function(xhr,errmsg,err) {
    console.log(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.