I'm currently working on sending data from JavaScript to Django using ajax. Below is the code snippet I am using for this:
var json_name = {'name': 123}
$.ajax({
method: 'POST',
url: 'my url',
contentType: "application/json",
headers: {
'Content-Type':'application/json',
'X-CSRFToken': "{{ csrf_token }}"
},
data: JSON.stringify(json_name),
success: function (data) {
//this gets called when server returns an OK response
alert("it worked!");
},
error: function (data) {
alert("it didnt work");
}
});
Below is the corresponding code in my Views.py file:
def myview(request):
if request.is_ajax():
request_data = request.body
# data = json.loads(request.body)
print(request_data)
# print(data)
return render(request, 'candidate/view.html')
else:
return render(request, 'candidate/view.html')
The output I receive is b''
When I attempt to include these lines:
data = json.loads(request.body)
print(data)
I encounter the following error:
TypeError: the JSON object must be str, not 'bytes'
I have referred to a similar issue on Stack Overflow here
If anyone could assist me with resolving this issue, please let me know if you require any additional information.