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.
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.
Share Improve this question edited Dec 20, 2019 at 16:43 Shahid Manzoor Bhat 1,3351 gold badge15 silver badges32 bronze badges asked Dec 20, 2019 at 16:37 Arthur ChoateArthur Choate 5336 silver badges21 bronze badges 2-
Can you show your
urls.py
file? – funnydman Commented Dec 21, 2019 at 11:07 - @funnydman I eventually figured this out. Posting answer now if you're curious. – Arthur Choate Commented Dec 26, 2019 at 14:58
2 Answers
Reset to default 9The 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'
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)