I'm attempting to make a GET
AJAX request to a Django view using vanilla JS. Despite passing is_ajax()
, I am having trouble properly retrieving the request object.
Below is my JavaScript code. Whether with or without JSON.stringify(data)
, it does not seem to be working.
document.querySelector('#testForm').onsubmit = () => {
let data = {category : 'music'};
const request = new XMLHttpRequest();
request.open('GET', 'test/', true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.onload = () => {
const data = JSON.parse(request.responseText);
console.log(data);
}
request.send(data);
return false;
});
And here is my Django view:
def test(request):
if request.is_ajax():
print('Yes!')
data = {'category': request.GET.get('category', None)}
return JsonResponse(data)
else:
raise Http404
While it displays Yes!
in the terminal, the console shows {category: null}
.
This jQuery snippet works as expected, providing the desired response {category: "music"}
:
$.ajax({
url: 'cart/',
type: 'GET',
data: data,
dataType: 'json',
success: function (data) {
console.log(data);
}
});
I'm unsure of what might be missing either in the vanilla JS code or within my Django view.