Reputation: 533
Javascript to send data via XMLHttpRequest
csrftoken = getCookie('csrftoken');
var request = new XMLHttpRequest();
request.open('POST', '/register');
request.setRequestHeader("X-CSRFToken", csrftoken);
request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
request.send("data");
Django view:
def register_user(request):
if request.method == "POST":
print("django server")
print(request.POST)
Sever is printing:
django server
<QueryDict: {}>
I have also triend application/json as content type with json data, but that is also not working. The data does not seem to be being passed to the server. Not sure why.
Upvotes: 2
Views: 2882
Reputation: 533
The request actually was being sent. This is how to access data:
def register_user(request):
if request.method == "POST":
print(request.body) # this would print "data"
In order for print(request.POST) to work the Content-Type must be 'application/x-www-form-urlencoded'
Upvotes: 9
Reputation: 835
Try this it works for me
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
@csrf_exempt
def register_user(request):
if request.is_ajax():
status = "1"
else:
status = "0"
return HttpResponse(status)
Upvotes: 0