I make a POST request via AJAX without HTML form. Are there any security issues? Why is there no csrf error? Because I do not send any csrf data and csrf is enabled in django?
toggle-status.js
jQuery(document).ready(function($) {
$("#switch-status").click(function(){
$.ajax({
url: '/account/switches/',
data: {'toggle': 'status'}
});
});
});
view.py
@login_required
def switches(request):
toggle = request.GET.get('toggle', None)
current_user = request.user
update = Switches.objects.get(owner=current_user)
if toggle == 'status':
if update.status is True:
update.status = False
else:
update.status = True
update.save()
return HttpResponse('')
The default method of the ajax function is a GET one, not a POST. So, doing a:
$.ajax({
url: '/account/switches/',
data: {'toggle': 'status'}
});
implies that an ajax GET is made. So, you're not doing a POST request.
If you want a POST request, do it like this:
$.ajax({
method: 'POST',
url: '/account/switches/',
data: {'toggle': 'status'}
});
Of course you have to include the CSRF token then, since it will fail if you try to POST without including one. Look here how to acomplish that.